BeautifulSoup属性错误:'get_text'在同一代码中有时出现

0 投票
1 回答
39 浏览
提问于 2025-04-14 15:53

有没有人知道这个问题是怎么回事?我运行同样的代码,有时候几秒钟就能跑完,但有时候却会出现这个错误,有时候又不会。

page = requests.get(URL, headers=headers)

soup1 = BeautifulSoup(page.content, 'html.parser')
soup2 = BeautifulSoup(soup1.prettify(), 'html.parser')
title = soup2.find(id='productTitle').get_text()
price = soup2.find(class_='aok-offscreen').get_text()

print(title)
print(price)

代码确实是一样的,我运行的时候,有时候会出现错误,有时候又能正常工作。我继续寻找元素,有时候能找到,有时候又找不到,谢谢大家。

---> 10 title = soup2.find(id='productTitle').get_text()
     11 price = soup2.find(class_='aok-offscreen').get_text()
     14 print(title)

AttributeError: 'NoneType' object has no attribute 'get_text'

1 个回答

0

问题在于,找不到一个ID为“productTitle”的元素。你可以尝试分开运行两个命令,比如

title_elem = soup2.find(id='productTitle')
print(title_elem)

这样会输出None。所以当你尝试在title_elem上使用get_text()方法时,像这样

print(title_elem.get_text())

这会产生一个错误。

撰写回答