使用newspaper3k爬取文章时无法获取发布日期及来源的解决方法
解决方案
newspaper3k的自动解析逻辑不一定适配所有网站的DOM结构,针对这个Delfi网站的特定元素,我们可以结合BeautifulSoup手动提取目标信息,具体修改如下:
步骤说明
- 引入
BeautifulSoup库解析下载后的HTML内容 - 通过标签和类名定位到
div.source-date和div.delfi-source-name元素 - 提取日期并转换为标准日期格式,提取来源/作者文本
- 将手动提取的信息替换原代码中无法自动获取的字段
修改后的完整代码
import newspaper from newspaper import Article import pandas as pd from bs4 import BeautifulSoup from datetime import datetime # 目标URL url = "https://www.delfi.lt/en/politics/foreign-ministry-tsikhanouskayas-consultation-needed-for-treating-belarusians-in-lithuania.d?id=91531501" article = Article(url) article.download() article.parse() article.nlp() # 解析下载的HTML内容 soup = BeautifulSoup(article.html, 'html.parser') # 提取发布日期 date_tag = soup.find('div', class_='source-date') published_date = None if date_tag: date_text = date_tag.get_text(strip=True) # 匹配网站日期格式,示例格式为"2024-05-29 12:30",需根据实际格式调整 published_date = datetime.strptime(date_text, "%Y-%m-%d %H:%M") # 提取来源/作者 source_tag = soup.find('div', class_='delfi-source-name') source_author = source_tag.get_text(strip=True) if source_tag else None # 构建数据表格 df = pd.DataFrame([{ 'Title': article.title, 'Author': source_author, 'Text': article.text, 'published_date': published_date, 'Source': article.source_url }]) df.to_excel('Delfi-1.xlsx', index=False)
注意事项
- 日期解析的格式字符串要和网站实际日期格式完全匹配,若网站日期格式变动需对应调整
- 若网站DOM结构(如类名、标签)修改,需重新定位目标元素
- 可添加异常处理逻辑,避免因元素不存在导致程序中断
内容的提问来源于stack exchange,提问作者Linda Brck
相关产品推荐
相关产品推荐

