Py学习  »  Python

python请求没有提取所有元素

lyesAlgerian • 6 年前 • 1844 次点击  

我正在尝试从以下页面提取tr数据: http://www.datasheetcatalog.com/catalog/p1342320.shtml

我正在使用请求和 BeautifulSoup . 但是,我没有得到所有行(第二个表中只有12行,而不是22行)。有人对此有解释吗(前提是在打印response.content时有行)?

下面是我使用的代码:

from bs4 import BeautifulSoup
import requests

session = requests.Session()

url = 'http://www.datasheetcatalog.com/catalog/p1342320.shtml'
response = session.get(url)

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

trs=  soup.findAll('table')[8].findAll('tr')
print (len(trs))
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41222
文章 [ 2 ]  |  最新文章 6 年前
ewwink
Reply   •   1 楼
ewwink    7 年前

HTML无效,已中断 BeautifulSoup 在这里修理

....
html_doc = response.text.replace('<table <', '<')
html_doc = re.sub(r'<\!--\s+\d+\s+--\!>', '', html_doc)
html_doc = re.sub(r'</?font.*?>' ,'', html_doc)
soup = BeautifulSoup(html_doc, "html.parser")

trs=  soup.findAll('table')[8].findAll('tr')
print (len(trs))

注:使用 lxml 返回7而不是22

lyesAlgerian
Reply   •   2 楼
lyesAlgerian    7 年前

经过对html页面的详细检查,我发现beautifulsoup在点击comments()之后停止了。因此,解决方案是将解析器从“lxml”更改为“html5lib”:

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