检查div类是否存在会返回错误

问题描述 投票:1回答:2

我在使用beautifulsoup登录一些产品后尝试从网页上删除网页。有一种情况是产品不再可用。该网页有一个div类,如下所示,仅在页面上没有产品

<div class="alert alert-danger">
    <p>There is an error</p>

所以我这样做

if soup.find_all('div', {'class': 'alert'}):
    print('Alert...')

要么

if soup.find_all('div', {'class': 'alert alert-danger'}):
    print('Alert...')

但我得到'int'对象在产品的位置没有属性文本

请求的状态代码是200

我怎样才能解决这个问题并取代空产品展示的东西?

python web-scraping beautifulsoup
2个回答
2
投票

嗯,也许,这是你的解决方案

from bs4 import BeautifulSoup
p = '<div class="alert alert-danger">\n<p>There is an error</p>'

alert = 'alert'    

soup = BeautifulSoup(p, 'html.parser').div['class']

if alert in list(soup):
    print("Alert....")

1
投票

我从你的代码示例中运行了if的内容:

soup.find_all('div', {'class': 'alert'})

soup.find_all('div', {'class': 'alert alert-danger'})

在这两种情况下,我得到:

[<div class="alert alert-danger">
 <p>There is an error</p>
 </div>]

所以我无法复制你的错误。也许你使用一些旧版本的BeautifulSoup?

我有4.7.1版。尝试升级BeautifulSoup的安装。

Edit

另一种方法是如何检查您的文档是否包含divclass="alert"元素:

if soup.find_all('div', class_='alert'):
    print("Alert....")

请注意,关键字参数最后包含_,以便与Python重新开发的单词(类)不同。这是BeautifulSoup的一个相对较新的功能。

© www.soinside.com 2019 - 2024. All rights reserved.