美丽的汤错误:' nontype'对象没有属性' find_all'

发布于 2025-02-12 22:24:43 字数 475 浏览 0 评论 0原文

我遇到此错误:

---> 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,它给出了属性错误。不知道为什么会发生这种情况。

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. Not sure why this is happening.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦情居士 2025-02-19 22:24:43

soup.find找不到任何东西时,它将返回。在中拨打s.find_all如果S:或not none:

因此,您的代码变为:

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/#查找

When soup.find does not find anything, it returns None. Guard your s.find_all call with if s: or if s in not None:.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文