web-scraping - Newspaper3k、用户代理和抓取
问题描述
我正在制作包含作者、出版日期和新闻文章正文的文本文件。我有代码可以做到这一点,但我需要Newspaper3k
首先从这些文章中识别相关信息。由于用户代理规范之前一直是个问题,所以我还指定了用户代理。这是我的代码,因此您可以跟随。这是Python 的。version 3.9.0
import time, os, random, nltk, newspaper
from newspaper import Article, Config
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
config = Config()
config.browser_user_agent = user_agent
url = 'https://www.eluniversal.com.mx/estados/matan-3-policias-durante-ataque-en-nochistlan-zacatecas'
article = Article(url, config=config)
article.download()
#article.html #
article.parse()
article.nlp()
article.authors
article.publish_date
article.text
为了更好地理解为什么这个案例特别令人费解,请将我上面提供的链接替换为这个链接,然后重新运行代码。使用此链接,代码现在可以正确运行,并返回作者、日期和文本。使用上面代码中的链接,它没有。我在这里俯瞰什么?
解决方案
显然,Newspaper 要求我们指定我们感兴趣的语言。这里的代码由于某种奇怪的原因仍然没有提取作者,但这对我来说已经足够了。这是代码,如果其他人会从中受益。
#
# Imports our modules
#
import time, os, random, nltk, newspaper
from newspaper import Article
from googletrans import Translator
translator = Translator()
# The link we're interested in
url = 'https://www.eluniversal.com.mx/estados/matan-3-policias-durante-ataque-en-nochistlan-zacatecas'
#
# Extracts the meta-data
#
article = Article(url, language='es')
article.download()
article.parse()
article.nlp()
#
# Makes these into strings so they'll get into the list
#
authors = str(article.authors)
date = str(article.publish_date)
maintext = translator.translate(article.summary).text
# Makes the list we'll append
elements = [authors+ "\n", date+ "\n", maintext+ "\n", url]
for x in elements:
print(x)
推荐阅读
- java - 检查Eureka Client是否已注册到Server的正确方法
- youtube-api - Youtube API 分析 - 如何获取订阅者的人口统计数据而不是观众
- angular - Angular:将自定义 HTTP 响应标头添加到 dev `ng serve`
- jquery - 使用 jquery 删除空格并从 div 中显示前 2 段
- python - Github binder requirements.txt
- azure - 从守护程序应用程序访问受 oAuth2 保护的 Azure 函数
- javascript - mapbox-gl 中两点位置之间的方向 - React Native?
- css - 如何使元素根据另一个元素定位?
- logstash - 使用 grok 过滤器插件跳过前几行日志
- android - Flutter - CupertinoDatePicker 在今天前一天显示?