AttributeError:“非类型”对象没有名为“全部查找”的属性

2024-10-01 19:33:02 发布

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

我目前正在制作一个webscraper来刮https://ncov2019.live/data/world,我在刮表头时遇到了麻烦。当我这样做的时候

head = soup.find('table',{"class" : "display responsive dataTable no-footer"}).find_all("tr")

table_header = head.find_all('th')

它回来了

Traceback (most recent call last):
File ".\ncov2019live.py", line 13, in <module>
head = soup.find('table',{"class" : "display responsive dataTable no-footer"}).find_all("tr")[1:]
AttributeError: 'NoneType' object has no attribute 'find_all'

Tags: nohttpsdisplaytableallfindheadtr
2条回答

正如我所见,该网站是客户端呈现。因此,您需要等待网站呈现所有数据

这就是为什么soup.find返回None对象

您正在查看的类可能是在客户端生成的,并且无法通过bs获得

如果您在debug中检查soup,您将看到一些有用的id可用,您可以使用这些id获取所需的信息(请参阅下面的代码)

from bs4 import BeautifulSoup
import requests

# get the BS object
url = "https://ncov2019.live/data/world"
req = requests.get(url)
soup = BeautifulSoup(req.content, "html.parser")

# if you look at all 'table's tag in debug you'll see all the available IDs
head = soup.find_all('table')  # < - not needed really. It's just for test

在这里,我们得到了列名称的表。此外,只有一个表具有此ID且只有一行,因此请使用find()而不是find_all()

head_th = soup.find(id='sortable_table_saved').find('tr')

# prints the field names
print('NAMES')
for th in head_th.find_all('th'):
    print(th.string)

在这里,我们得到了带有值的表。这里find_all()是必要的

items = soup.find(id='sortable_table_world').find_all('tr')
print('ITEMS')

for tr in items:
    print(tr)

祝你好运

相关问题 更多 >

    热门问题