[英]Beautiful Soup error: 'NoneType' object has no attribute 'find_all'
I am getting this error:我收到此错误:
---> 14 content = s.find_all('p')
AttributeError: 'NoneType' object has no attribute 'find_all'
While running the script below:运行以下脚本时:
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)
It's working for some URLs, but for other URLs it gives an attribute error.它适用于某些 URL,但对于其他 URL,它会给出属性错误。 Not sure why this is happening.
不知道为什么会这样。
When soup.find
does not find anything, it returns None
.当
soup.find
没有找到任何东西时,它返回None
。 Guard your s.find_all
call with if s:
or if s in not None:
.使用
if s:
或if s in not None:
保护您的s.find_all
呼叫。
So your code becomes:所以你的代码变成:
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...")
or maybe:或者可能:
content = s.find_all('p') if s is not None else []
print(content)
Ref: https://crummy.com/software/BeautifulSoup/bs4/doc/#find参考: https ://crummy.com/software/BeautifulSoup/bs4/doc/#find
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.