【问题标题】:Python urllib is not extracting reader comments from a websitePython urllib 没有从网站中提取读者评论
【发布时间】:2017-02-24 06:40:29
【问题描述】:

我正在尝试使用下面显示的代码从下一页提取阅读器 cmets。但输出 html test.html 不包含页面中的任何 cmets。如何使用 Python 获取这些信息?

http://www.theglobeandmail.com/opinion/it-doesnt-matter-who-won-the-debate-america-has-already-lost/article32314064/comments/

from bs4 import BeautifulSoup
import urllib
import urllib.request
import urllib.parse

req =urllib.request.Request('http://www.theglobeandmail.com/opinion/it-doesnt-matter-who-won-the-debate-america-has-already-lost/article32314064/comments/')
response = urllib.request.urlopen(req)
the_page = response.read()

soup = BeautifulSoup(the_page, 'html.parser')
f = open('test.html', 'w')
f.write(soup.prettify())
f.close()

谢谢!

【问题讨论】:

  • cmets最有可能是用js检索的。您可以使用包含浏览器 + js 运行时(pahtomjs 等)的抓取库,也可以尝试找出用于提取 cmets 的 api 是什么并直接使用它。

标签: python web-scraping urllib


【解决方案1】:

使用您可以模仿的 ajax 请求检索 cmets:

您可以看到有许多参数,但以下内容足以获得结果,我将留给您弄清楚如何影响结果:

from json import loads
from urllib.request import  urlopen
from urllib.parse import urlencode

data = {"categoryID":"Production",
    "streamID":"32314064",
    "APIKey":"2_oNjjtSC8Qc250slf83cZSd4sbCzOF4cCiqGIBF8__5dWzOJY_MLAoZvds76cHeQD",
    "callback" :"foo",}
r = urlopen("http://comments.us1.gigya.com/comments.getComments", data=urlencode(data).encode("utf-8"))
json_dcts = loads(r.read().decode("utf-8"))["comments"]

print(json_dcts)

这为您提供了包含所有 cmets、upvotes、negvotes 等的 dicts 列表。如果您想解析密钥,它位于其中一个脚本 src='https://cdns.gigya.com/js/socialize.js?apiKey=2_oNjjtSC8Qc250slf83cZSd4sbCzOF4cCiqGIBF8__5dWzOJY_MLAoZvds76cHeQD' 的 url 中,streamID 在您的原始网址中。

【讨论】:

  • 感谢您的回复!我试过了,它奏效了。但我有几个问题:
  • 首先,您从哪里获得 url:comments.us1.gigya.com,其次,您如何使用 Python 发送 ajax 查询以获取所有键值对以创建适当的数据字典。我对ajax查询一无所知。能否请您指出一个了解 ajax 的好来源?
  • @user7009553,打开 firebug/chrome 工具等。在 XHR 下的网络选项卡下查看,您可以看到正在发出的请求。 ajax -> 异步 JavaScript 和 XML developer.mozilla.org/en-US/docs/AJAX/Getting_Started
猜你喜欢
  • 2016-08-16
  • 2021-09-15
  • 2023-02-11
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 2018-09-22
相关资源
最近更新 更多