我想用9gag feed(以及后来的其他图像板)中的帖子构建一个语料库。为此,我尝试提取源html代码。不幸的是,只要我想在html代码中找到feed中的文章,似乎文章没有与html代码一起提取。当我在feed中搜索某些内容时,使用.find()始终返回-None-。
我此时使用了lxml,html.parser和html5lib:
soup = BeautifulSoup(source, 'html5lib')
我搜索了各种关键字,这些关键字显示在我的浏览器向我显示的代码中,此时:
entry = soup.find('div')
比较浏览器检查器和汤变量中的代码,我会得到不同的结果。检查员找到汤变量找不到的关键字。
我试图将requests.get
函数的输出从.text
更改为.content
,但仍然不会出现所需的代码
##get source text of 9gag
source = requests.get('https://9gag.com').text
##make source a soup-type
soup = BeautifulSoup(source, 'html5lib')
##clip out the needed code of html for entrys
entry = soup.find('div id')
如何分别获得9gag Feed的完整代码以及构成单独帖子的代码?
还有什么可能出错?
似乎数据是作为JSON接收的,所以最好只使用requests
和JSON
库来完成这项任务。所以你的代码应该是这样的:
import requests
import json
url = "https://9gag.com"
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0"}
req = requests.get(url, headers=headers).text
json_raw = req[req.index("{\"page\":"):req.index("}})")+2]
posts = json.loads(json_raw)["data"]['posts']
希望这可以帮助