Python 属性错误:“NoneType”对象没有属性“find_all”

问题描述 投票:0回答:3

我正在尝试获取美国各州的缩写,但此代码:

from bs4 import BeautifulSoup
from urllib.request import urlopen
url='https://simple.wikipedia.org/wiki/List_of_U.S._states'
web=urlopen(url)
source=BeautifulSoup(web, 'html.parser')
table=source.find('table', {'class': 'wikitable sortable jquery-tablesorter'})
abbs=table.find_all('b')
print(abbs.get_text())

返回 AttributeError: 'Nonetype' 对象没有属性 'find_all'。我的代码有什么问题?

python python-3.x beautifulsoup attributeerror
3个回答
1
投票

正如Patrick所建议的那样,

source.first() 只返回第一个元素。

first()方法源码供参考:

def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs):
    """Return only the first child of this Tag matching the given criteria."""
    r = None
    l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
    if l:
        r = l[0]
    return r
findChild = find

提取表后,它的类名是

wikitable sortable
.
所以按照上面的代码,它正在返回
None
.

所以您可能想将代码更改为...

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = 'https://simple.wikipedia.org/wiki/List_of_U.S._states'
web = urlopen(url)
source = BeautifulSoup(web, 'html.parser')

table = source.find('table', class_='wikitable')
abbs = table.find_all('b')

abbs_list = [i.get_text().strip() for i in abbs]
print(abbs_list)

我希望它能回答你的问题。 :)


1
投票

给你。

我将source.find中的类更改为

'wikitable sortable'
。另外,方法
abbs.get_text()
给了我一个错误,所以我只是使用生成器函数来获取你想要的文本。

from bs4 import BeautifulSoup
from urllib.request import urlopen

web = urlopen('https://simple.wikipedia.org/wiki/List_of_U.S._states')
source = BeautifulSoup(web, 'lxml')
table = source.find(class_='wikitable sortable').find_all('b')
b_arr = '\n'.join([x.text for x in table])
print(b_arr)

部分输出:

AL
AK
AZ
AR
CA
CO

0
投票

正如评论中所建议的,网址中的 HTML 没有包含该类的表格

'wikitable sortable jquery-tablesorter'

但班级其实是

'wikitable sortable'

此外,一旦您应用 find_all,它会返回一个包含所有标签的列表,因此您不能直接对其应用 get_text()。您可以使用列表理解来去除列表中每个元素的文本。这是适用于您的问题的代码

from bs4 import BeautifulSoup
from urllib.request import urlopen
url='https://simple.wikipedia.org/wiki/List_of_U.S._states'
web=urlopen(url)
source=BeautifulSoup(web, 'html.parser')
table=source.find('table', {'class': 'wikitable sortable'})
abbs=table.find_all('b')
values = [ele.text.strip() for ele in abbs]
print(values)
© www.soinside.com 2019 - 2024. All rights reserved.