【问题标题】:How can I retrieve titles of various articles from one website using python web scraping?如何使用 python 网络抓取从一个网站检索各种文章的标题?
【发布时间】:2018-08-29 17:29:31
【问题描述】:

我正在寻找使用 python 网络爬虫获取此网页“”中所有可用文章的主题。我对html很陌生。这是迄今为止我从不同示例中获得的代码作为参考。有人可以帮我理解这一点并获得正确的代码吗?

下面的代码是我尝试将 h2 标签更改为 h1、h3、h4 等的代码。

from urllib2 import urlopen

from urllib2 import HTTPError

from urllib2 import URLError

from bs4 import BeautifulSoup

try:

     html = urlopen("https://query.nytimes.com/search/sitesearch/#/*/365days/")
except HTTPError as e:

    print(e)

except URLError:

    print("Server down or incorrect domain")

else:

    res = BeautifulSoup(html.read(),'html.parser')

    tags = res.findAll("h2", {"class": "widget-title"})


    for tag in tags:

        print(tag.getText())

我的预期结果是此网页中各种新文章的标题。例如:

法官在蔑视听证会上严厉批评科巴赫

自动驾驶优步如何杀死亚利桑那州的行人

【问题讨论】:

  • 到目前为止您尝试过什么?你期待的具体结果是什么?您的结果与预期有何不同?
  • 该页面使用 javascript 填充。您需要使用像 selenium 包中包含的那样的无头浏览器,或者调用发出页面最终发出的相同请求,而不是尝试加载页面本身。
  • @MohammadAthar 感谢您的反馈,我已经编辑了我的问题。我对这个主题相当陌生,所以如果你能提供帮助会很棒。
  • @wpercy 感谢您提供的信息。我不明白提出与页面结束相同的请求的部分?

标签: python html python-2.7 web


【解决方案1】:

每次进入页面

https://query.nytimes.com/search/sitesearch/#/*/365days/

在页面加载时执行的 javascript 请求位于

的资源
https://query.nytimes.com/svc/add/v1/sitesearch.json?begin_date=365daysago&facet=true

这会返回一个包含搜索结果的非常大的 JSON 文档,您可以对其进行解析以获取文章标题。代码看起来像:

import json
from urllib2 import urlopen, HTTPError, URLError

resp = urlopen("https://query.nytimes.com/svc/add/v1/sitesearch.json?q=quack&begin_date=365daysago&facet=true")
content = resp.read()
j = json.loads(content)

articles = j['response']['docs']

headlines = [ article['headline']['main'] for article in articles ]
print headlines

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 2022-08-04
    • 1970-01-01
    • 2017-05-03
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    相关资源
    最近更新 更多