如何通过带有清爽Feed的网站上的beautifulsoup提取完整的html代码?

问题描述 投票:0回答:1

我想用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的完整代码以及构成单独帖子的代码?

还有什么可能出错?

python python-3.x web-scraping beautifulsoup feed
1个回答
1
投票

似乎数据是作为JSON接收的,所以最好只使用requestsJSON库来完成这项任务。所以你的代码应该是这样的:

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']

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.