使用 BeautifulSoup 时出现 AttributeError: 'str' 对象没有属性 'descendants' 错误

fac*_*asd 2 python beautifulsoup python-3.x

@ayivima 有一个很好的答案,但我应该补充一点,该网站本身最终没有被 BeautifulSoup 正确抓取,因为它有大量的 Javascript。


所以我对使用Python完全陌生,我只是想打印网页的标题。我主要使用来自谷歌的代码:

from bs4 import BeautifulSoup, SoupStrainer
import requests

url = "https://www150.statcan.gc.ca/t1/tbl1/en/tv.action?pid=3210001601"
page = requests.get(url)
data = page.text
soup = BeautifulSoup
soup.find_all('h1')

print(text)
Run Code Online (Sandbox Code Playgroud)

我不断收到错误:

AttributeError: 'str' object has no attribute 'descendants'
Run Code Online (Sandbox Code Playgroud)

老实说,我真的不知道这意味着什么,我能找到的唯一其他答案来自:AttributeError: 'str' object has no attribute 'descendants'我认为这不适用于我?

我在代码中做错了什么吗?(可能很多,但我的意思主要是为了这个错误)

ayi*_*ima 5

BeautifulSoup 需要一个 html 解析器,并且 html 文本作为属性传递。从技术上讲,您需要创建一个 BeautifulSoup 实例。如果不传递 html 文本,将没有任何内容可供搜索。

所以该行soup = BeautifulSoup必须变成这样:

soup = BeautifulSoup(data, 'html.parser')
Run Code Online (Sandbox Code Playgroud)

其中第一个参数在本例data中指的是原始 html 文本,第二个参数是解析器html.parser。我使用默认的 python html 解析器,但 python 支持其他解析器。在这里了解更多信息:https://www.crummy.com/software/BeautifulSoup/bs4/doc/

推荐代码:

from bs4 import BeautifulSoup, SoupStrainer
import requests

url = "https://www150.statcan.gc.ca/t1/tbl1/en/tv.action?pid=3210001601"
page = requests.get(url)
data = page.text
soup = BeautifulSoup(data, 'html.parser')
text = soup.find_all('h1')

print(text)
Run Code Online (Sandbox Code Playgroud)

输出:

[]
Run Code Online (Sandbox Code Playgroud)

BeautifulSoup 似乎没有找到任何h1标签。

让我们尝试一下meta标签:

meta_tags = soup.find_all('meta')
print(meta_tags)
Run Code Online (Sandbox Code Playgroud)

输出:

[<meta content="no-cache" http-equiv="Pragma"/>, 
<meta content="-1" http-equiv="Expires"/>, 
<meta content="no-cache" http-equiv="CacheControl"/>]
Run Code Online (Sandbox Code Playgroud)