Python urllib 未从网站提取 reader 评论

Python urllib is not extracting reader comments from a website

我正在尝试使用下面显示的代码从下一页提取 reader 评论。但是输出 html test.html 不包含来自页面的任何评论。我如何使用 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()

谢谢!

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

您可以看到有很多参数,但下面的内容足以得出一个结果,我会留给您来弄清楚您如何影响结果:

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)

这为您提供了一个字典列表,其中包含所有评论、赞成票、反对票等。如果您想解析密钥,它位于其中一个脚本 url 中 src='https://cdns.gigya.com/js/socialize.js?apiKey=2_oNjjtSC8Qc250slf83cZSd4sbCzOF4cCiqGIBF8__5dWzOJY_MLAoZvds76cHeQD', streamID 是你原来的 url.