如何通过 beautifulsoup 从具有刷新提要的网站提取完整的 html 代码?
How do I extract a full html-code via beautifulsoup from a website with a refreshing feed?
我想用来自 9gag 提要(以及后来的其他图像板)的帖子构建一个语料库。为此,我尝试提取源 html 代码。不幸的是,当我想从 html 代码中的提要中找到文章时,这些文章似乎没有与 html 代码一起提取。总是使用 .find() returns -None- 当我在提要中搜索内容时。
此时我使用了 lxml、html.parser 和 html5lib:
soup = BeautifulSoup(source, 'html5lib')
我搜索了各种关键字,这些关键字出现在我的浏览器显示给我的代码中,此时:
entry = soup.find('div')
比较浏览器检查器中的代码和 soup 变量中的代码,我得到了不同的结果。检查员找到 soup 变量找不到的关键字。
我尝试将 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 提要的完整代码和构成单独帖子的代码?
还有什么地方可能出了问题?
看来数据是作为 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']
希望对您有所帮助
我想用来自 9gag 提要(以及后来的其他图像板)的帖子构建一个语料库。为此,我尝试提取源 html 代码。不幸的是,当我想从 html 代码中的提要中找到文章时,这些文章似乎没有与 html 代码一起提取。总是使用 .find() returns -None- 当我在提要中搜索内容时。
此时我使用了 lxml、html.parser 和 html5lib:
soup = BeautifulSoup(source, 'html5lib')
我搜索了各种关键字,这些关键字出现在我的浏览器显示给我的代码中,此时:
entry = soup.find('div')
比较浏览器检查器中的代码和 soup 变量中的代码,我得到了不同的结果。检查员找到 soup 变量找不到的关键字。
我尝试将 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 提要的完整代码和构成单独帖子的代码?
还有什么地方可能出了问题?
看来数据是作为 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']
希望对您有所帮助