gpt4 book ai didi

python - 相同的 CSS,浏览器和 bs4 .select() 方法中的不同结果

转载 作者:行者123 更新时间:2023-12-01 08:34:54 24 4
gpt4 key购买 nike

我正在尝试从以下网页检索一些信息: https://web.archive.org/web/19990421025223/http://www.rbc.ru

我构建了一个选择器,它在 Chrome 的检查模式下突出显示所需的表格:

selector = 'body > table:nth-of-type(2) > tbody:nth-of-type(1)>tr:nth-of-type(1)>td:nth-of-type(5)>table:nth-of-type(1)>tbody:nth-of-type(1)'

但是,当使用 bs4 .select() 方法运行脚本时:

import requests
from bs4 import BeautifulSoup
import lxml

url = 'https://web.archive.org/web/19990421025223/http://www.rbc.ru'
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
}
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
selector = 'body > table:nth-of-type(2) > tbody:nth-of-type(1)>tr:nth-of-type(1)>td:nth-of-type(5)>table:nth-of-type(1)>tbody:nth-of-type(1)'
print(soup.select(selector=selector))

输出是:[] - 这与预期的非常不同,因为它由浏览器中的 html 代码组成。

我在这里缺少什么?

最佳答案

您不能指望浏览器生成的选择器能够在 BeautifulSoup 中可靠地工作,因为当在浏览器中呈现页面时,标记会发生变化,而当您在在您的 Python 代码中,没有渲染,您只能得到最初的非渲染 HTML 页面。

在这里,您必须想出自己的 CSS 选择器或其他方法来定位 table 元素。

由于页面的标记并不是真正适合 HTML 解析的,因此我将通过其中一个列名称来定位 table 元素:

table = soup.find("b", text="спрос").find_parent("table")

请注意,它仅在我使用 lenient html5lib parser 解析页面时才有效。 :

soup = BeautifulSoup(response.content, "html5lib")

关于python - 相同的 CSS,浏览器和 bs4 .select() 方法中的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53771862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com