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.
63 lines
1.9 KiB
63 lines
1.9 KiB
package controller;
|
|
|
|
import model.NovelRank;
|
|
import strategy.CrawlerStrategy;
|
|
import strategy.FanqieNovelStrategy;
|
|
import strategy.QidianNovelStrategy;
|
|
import strategy.ChangchenNovelStrategy;
|
|
import exception.CrawlerException;
|
|
import exception.ValidationException;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.List;
|
|
import java.util.ArrayList;
|
|
|
|
public class CrawlerController {
|
|
private Map<String, CrawlerStrategy> strategies;
|
|
|
|
public CrawlerController() {
|
|
this.strategies = new HashMap<>();
|
|
initializeStrategies();
|
|
}
|
|
|
|
private void initializeStrategies() {
|
|
addStrategy(new FanqieNovelStrategy());
|
|
addStrategy(new QidianNovelStrategy());
|
|
addStrategy(new ChangchenNovelStrategy());
|
|
}
|
|
|
|
public void addStrategy(CrawlerStrategy strategy) {
|
|
strategies.put(strategy.getSiteName(), strategy);
|
|
}
|
|
|
|
public CrawlerStrategy getStrategy(String siteName) {
|
|
CrawlerStrategy strategy = strategies.get(siteName);
|
|
if (strategy == null) {
|
|
throw new ValidationException("未知的网站: " + siteName);
|
|
}
|
|
return strategy;
|
|
}
|
|
|
|
public NovelRank crawlSite(String siteName) throws CrawlerException {
|
|
CrawlerStrategy strategy = getStrategy(siteName);
|
|
return strategy.crawl();
|
|
}
|
|
|
|
public List<NovelRank> crawlAllSites() throws CrawlerException {
|
|
List<NovelRank> ranks = new ArrayList<>();
|
|
for (CrawlerStrategy strategy : strategies.values()) {
|
|
try {
|
|
NovelRank rank = strategy.crawl();
|
|
ranks.add(rank);
|
|
} catch (CrawlerException e) {
|
|
System.err.println("[ERROR] 爬取 " + strategy.getSiteName() + " 失败: " + e.getMessage());
|
|
}
|
|
}
|
|
return ranks;
|
|
}
|
|
|
|
public List<String> getAvailableSites() {
|
|
return new ArrayList<>(strategies.keySet());
|
|
}
|
|
}
|