【问题标题】:Get web article information (content , title, ...) from multiple web pages-python code从多个网页中获取网页文章信息(内容、标题、...)-python 代码
【发布时间】:2021-01-10 23:57:44
【问题描述】:

有一个 python 库 - Newspaper3k,它使获取网页内容变得更容易。 [newspaper][1]

用于标题检索:

import newspaper
a = Article(url)
print(a.title)

对于内容检索:

url = 'http://fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones/'
article = Article(url)
article.text

我想获取有关网页的信息(有时是标题,有时是实际内容)有我的代码来获取网页的内容/文本:

from newspaper import Article
import nltk
nltk.download('punkt')
fil=open("laborURLsml2.csv","r") 
# 3, below read every line in fil
Lines = fil.readlines()
for line in Lines:
    print(line)
    article = Article(line)
    article.download()
    article.html
    article.parse()
    print("[[[[[")
    print(article.text)
    print("]]]]]")

“laborURLsml2.csv”文件的内容是: [laborURLsml2.csv][2]

我的问题是:我的代码读取了第一个 URL 并打印了内容,但未能继续读取 2 个 URL

【问题讨论】:

  • 您在处理第一个 url 时是否看到任何异常?
  • 是的,抛出了这个异常:" raise ArticleException('Article download() failed with %s on URL %s' % ArticleException: Article download() failed with 404 Client Error: Not Found for url : socialeurope.eu/… 在 URL socialeurope.eu/…"
  • 你能把完整的异常信息放上去吗?或者将for 循环的处理部分包装在try/except 块中
  • 是的,我将 for 循环包装在 try/except 块中。并将“laborURLsml2.csv”的所有网址放在一个列表中。有用。我认为 newsletter3k 库对 URL 末尾的“/”等特殊字符很敏感
  • @tursunWali news3k 对 URL 末尾的特殊字符“/”不敏感,但对 CSV 中的尾随空格很敏感。我在回答中用 .strip() 删除了它。在使用 Newspaper 时使用“USER_AGENT 和 timeout 也是一个好习惯。我注意到在提取文章文本时需要进行一些数据清理。

标签: python python-3.x web-scraping newspaper3k


【解决方案1】:

我注意到您的 CSV 文件中的某些 URL 有一个尾随空格,这导致了问题。我还注意到您的其中一个链接不可用,而其他链接则是分发给子公司以供发布的相同故事。

下面的代码处理了前两个问题,但没有处理数据冗余问题。

from newspaper import Config
from newspaper import Article
from newspaper import ArticleException

USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Firefox/78.0'

config = Config()
config.browser_user_agent = USER_AGENT
config.request_timeout = 10

with open('laborURLsml2.csv', 'r') as file:
    csv_file = file.readlines()
    for url in csv_file:
        try:
            article = Article(url.strip(), config=config)
            article.download()
            article.parse()
            print(article.title)
            # the replace is used to remove newlines
            article_text = article.text.replace('\n', ' ')
            print(article_text)
        except ArticleException:
            print('***FAILED TO DOWNLOAD***', article.url)

您可能会发现我在Github page 上创建并分享的这个newspaper3K overview document 很有用。

【讨论】:

  • 谢谢。有没有一种方法可以让时事通讯处理存储的文本?
  • “存储的文本”是什么意思?
  • 存储的文本,我的意思是有.txt格式或.csv格式的文本/内容。比方说,在每个 csv 元素中有一个文本:“ text ”、“ text 2”、“ text 3” 。如何在这些文本上使用“article.keyword”、“article.summary”?
  • @tursunWali 是的,这可以做到。打开另一个问题,我会在您接受此问题后为您解答。
  • 感谢您提供的上述解决方案非常棒。我打开了一个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2010-12-23
  • 2015-11-03
相关资源
最近更新 更多