繁体   English   中英

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

[英]Beautiful Soup error: 'NoneType' object has no attribute 'find_all'

我收到此错误:

---> 14 content = s.find_all('p')
AttributeError: 'NoneType' object has no attribute 'find_all'

运行以下脚本时:

r = requests.get('https://www.marketsandmarkets.com/Market-Reports/rocket-missile-market-203298804.html/')
soup = BeautifulSoup(r.content, 'html.parser')
s = soup.find('div', class_='entry-content') 
content = s.find_all('p')
print(content)   

它适用于某些 URL,但对于其他 URL,它会给出属性错误。 不知道为什么会这样。

soup.find没有找到任何东西时,它返回None 使用if s:if s in not None:保护您的s.find_all呼叫。

所以你的代码变成:

r = requests.get('https://www.marketsandmarkets.com/Market-Reports/rocket-missile-market-203298804.html/')
soup = BeautifulSoup(r.content, 'html.parser')
s = soup.find('div', class_='entry-content') 
if s is not None:
    content = s.find_all('p')
    print(content) 
else:
    print("Didn't find what I was looking for...")

或者可能:

content = s.find_all('p') if s is not None else []
print(content)

参考: https ://crummy.com/software/BeautifulSoup/bs4/doc/#find

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM