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.
 
 

95 lines
3.5 KiB

package com.example.datacollect.strategy;
import com.example.datacollect.model.Article;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class HnuNewsStrategy implements CrawlStrategy {
// 1. 添加 Logger 成员
private static final Logger logger = LoggerFactory.getLogger(HnuNewsStrategy.class);
// 2. 修正 URL 匹配逻辑(原逻辑仅匹配域名,建议增加路径灵活性)
private static final Pattern URL_PATTERN = Pattern.compile(".*news\\.hnu\\.edu\\.cn.*");
@Override
public boolean supports(String url) {
return URL_PATTERN.matcher(url).matches();
}
@Override
public List<Article> parse(String url, Document doc) {
List<Article> articles = new ArrayList<>();
// 原有逻辑:尝试选择列表项
// 注意:根据2026年5月的网页结构,实际可能需要调整为 div 或其他容器
Elements listItems = doc.select("ul.list11 li");
if (listItems.isEmpty()) {
logger.warn("在 URL [{}] 中未找到符合选择器 'ul.list11 li' 的新闻列表项。可能网页结构已更新。", url);
return articles;
}
for (Element li : listItems) {
Element link = li.selectFirst("a");
if (link == null) {
logger.debug("跳过一个无链接的列表项: {}", li.toString());
continue;
}
String articleUrl = link.attr("href");
// 3. 修正 URL 拼接逻辑(原逻辑 replace("..") 可能不够健壮)
if (!articleUrl.startsWith("http")) {
// 使用 URI 或简单的字符串处理来规范化路径
articleUrl = "https://news.hnu.edu.cn/" + articleUrl;
// 这里简单处理,实际可能需要更复杂的路径规范化
while (articleUrl.contains("/../")) {
int index = articleUrl.indexOf("/../");
int prevSlash = articleUrl.lastIndexOf('/', index - 1);
if (prevSlash != -1) {
articleUrl = articleUrl.substring(0, prevSlash) + articleUrl.substring(index + 3);
} else {
break;
}
}
}
String title = "";
Element titleEl = link.selectFirst("h4.l2.h4s2");
if (titleEl != null) {
title = titleEl.text().trim();
} else {
logger.debug("在链接 [{}] 中未找到标题元素 h4.l2.h4s2", articleUrl);
}
String content = "";
Element contentEl = link.selectFirst("p.l3.ps3");
if (contentEl != null) {
content = contentEl.text().trim();
}
// 不再输出空内容警告,因 content 可能为空
if (!title.isEmpty()) {
articles.add(new Article(title, articleUrl, content));
logger.debug("解析到新闻条目: [标题] {} - [URL] {}", title, articleUrl);
} else {
logger.trace("跳过空标题的链接: {}", articleUrl);
}
}
logger.info("成功解析 URL [{}],共提取 {} 篇新闻。", url, articles.size());
return articles;
}
@Override
public int getPriority() {
return 15;
}
}