BeautifulGroup无法从wiki中提取表

2024-06-16 11:37:17 发布

您现在位置:Python中文网/ 问答频道 /正文

当我检查桌子的时候 在

<table class="wikitable sortable jquery-tablesorter">

所以我在Python中尝试了以下方法: 在

^{pr2}$

但是,我得到了一个空列表。有什么想法吗?在


Tags: 方法列表tablejqueryclass桌子sortabletablesorter
2条回答

在对列进行排序之前,导航网站时不会出现表类wikitable sortable jquery-tablesorter。通过使用table类wikitable sortable,我只获得了一个表。在

import requests
from bs4 import BeautifulSoup

res = requests.get("https://en.wikipedia.org/wiki/Comparison_of_Intel_processors")
soup = BeautifulSoup(res.content, "html.parser")
tables = soup.find_all("table", class_="wikitable sortable")
print(len(tables))

注意事项:

  • 我在您的示例中使用了class_=而不是字典,因为standford.edu tutorial on Beautiful Soup。在
  • BeautifulSoup类中定义了一个名为html.parser的解析器,因此代码可以按照打印的警告在不同的环境下工作。在

试试下面的方法。它将从该网站获取表格数据:

import requests
from bs4 import BeautifulSoup

res = requests.get("https://en.wikipedia.org/wiki/Comparison_of_Intel_processors")                                                  
soup = BeautifulSoup(res.text, 'lxml') #if you find any problem with "lxml" then try using "html.parser" instead
table = soup.find("table",class_="wikitable")
for items in table.find_all("tr")[:-1]:
    data = [' '.join(item.text.split()) for item in items.find_all(['th','td'])]
    print(data)

部分输出:

^{pr2}$

相关问题 更多 >