You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
122 lines
3.4 KiB
122 lines
3.4 KiB
package controller;
|
|
|
|
import view.ConsoleView;
|
|
import model.Article;
|
|
import strategy.*;
|
|
import command.*;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
public class CrawlerController {
|
|
private ConsoleView view;
|
|
private List<Article> articles;
|
|
private List<CrawlStrategy> strategies;
|
|
|
|
public CrawlerController() {
|
|
this.view = new ConsoleView();
|
|
this.articles = new ArrayList<>();
|
|
this.strategies = new ArrayList<>();
|
|
|
|
strategies.add(new JjwxcStrategy());
|
|
strategies.add(new BaiduStrategy());
|
|
strategies.add(new HttpBinStrategy());
|
|
strategies.add(new BingStrategy());
|
|
}
|
|
|
|
public ConsoleView getView() {
|
|
return view;
|
|
}
|
|
|
|
public List<Article> getArticles() {
|
|
return articles;
|
|
}
|
|
|
|
public void addArticle(Article article) {
|
|
articles.add(article);
|
|
}
|
|
|
|
public void clearArticles() {
|
|
articles.clear();
|
|
}
|
|
|
|
public String[] getStrategyNames() {
|
|
String[] names = new String[strategies.size()];
|
|
for (int i = 0; i < strategies.size(); i++) {
|
|
names[i] = strategies.get(i).getName();
|
|
}
|
|
return names;
|
|
}
|
|
|
|
public void run() {
|
|
view.showWelcome();
|
|
view.showHelp();
|
|
|
|
boolean running = true;
|
|
while (running) {
|
|
String input = view.getInput();
|
|
|
|
if (input.isEmpty()) {
|
|
continue;
|
|
}
|
|
|
|
switch (input) {
|
|
case "1":
|
|
case "jjwxc":
|
|
executeCommand(new CrawlCommand(strategies.get(0), this));
|
|
break;
|
|
|
|
case "2":
|
|
case "baidu":
|
|
executeCommand(new CrawlCommand(strategies.get(1), this));
|
|
break;
|
|
|
|
case "3":
|
|
case "httpbin":
|
|
executeCommand(new CrawlCommand(strategies.get(2), this));
|
|
break;
|
|
|
|
case "4":
|
|
case "bing":
|
|
executeCommand(new CrawlCommand(strategies.get(3), this));
|
|
break;
|
|
|
|
case "all":
|
|
crawlAll();
|
|
break;
|
|
|
|
case "list":
|
|
executeCommand(new ListCommand(this));
|
|
break;
|
|
|
|
case "save":
|
|
executeCommand(new SaveCommand(this));
|
|
break;
|
|
|
|
case "help":
|
|
executeCommand(new HelpCommand(this));
|
|
break;
|
|
|
|
case "exit":
|
|
case "quit":
|
|
running = false;
|
|
view.showGoodbye();
|
|
break;
|
|
|
|
default:
|
|
view.showError("未知命令: " + input + ",输入 help 查看帮助");
|
|
}
|
|
}
|
|
}
|
|
|
|
private void executeCommand(Command command) {
|
|
command.execute();
|
|
}
|
|
|
|
private void crawlAll() {
|
|
view.showMessage("\n开始爬取所有网站...\n");
|
|
for (CrawlStrategy strategy : strategies) {
|
|
executeCommand(new CrawlCommand(strategy, this));
|
|
}
|
|
view.showMessage("\n全部爬取完成!共 " + articles.size() + " 条数据");
|
|
}
|
|
}
|
|
|