python - bs4 在给定标签的所有属性中搜索一个词

标签 python html selenium-webdriver web-scraping beautifulsoup

我正在开发一个网络抓取工具来查找给定网站的价格标签。

我有密码

price = soup.findAll(['div'],{'class':re.compile(r'(.*?price.*?)',re.IGNORECASE)})

有了这个,我能够找到所有带有 class 属性的 div 标签,这些标签的值带有 price 关键字。 (包含价格的词,如数据价格、价格等)

但我想检索所有包含 price 关键字的 div 标签,而不考虑属性名称。

例子:

我要抓取的网站格式如下:

<div class="css-2vqe5n esdkp3p0" data-automation="buybox-price" aria-label="Now $74">$74</div>

我的代码仅在类属性中存在 price 关键字时进行检索,但在这种情况下,它存在于数据自动化属性中。

所以我正在寻找一种解决方案,它可以搜索 div 标签的所有属性,而不仅仅是在类标签中搜索。

最佳答案

对于此任务,您可以使用带有自定义函数的 .find_all()

例如:

from bs4 import BeautifulSoup


html_text = '''
<div class="css-2vqe5n esdkp3p0" data-automation="buybox-price" aria-label="Now $74">$74</div>
<div class="price value" aria-label="Now $75">$75</div>
<div class="discount-price" aria-label="Now $76">$76</div>
<div class="something_other">other</div>
'''

soup = BeautifulSoup(html_text, 'html.parser')

def is_price(tag):
    for k, v in tag.attrs.items():
        if 'price' in v:
            return True
        elif isinstance(v, list) and any('price' in i for i in v):
            return True


for tag in soup.find_all(is_price):
    print(tag)

打印:

<div aria-label="Now $74" class="css-2vqe5n esdkp3p0" data-automation="buybox-price">$74</div>
<div aria-label="Now $75" class="price value">$75</div>
<div aria-label="Now $76" class="discount-price">$76</div>

关于python - bs4 在给定标签的所有属性中搜索一个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63161086/

相关文章:

python - 如何返回 bool 值列表以查看一个列表的元素是否在另一个列表中

html - 无法更改按钮的背景颜色

javascript - 输入电子邮件地址后,我需要司机按标签两次

c# - 从字符串中检索货币符号

java - Selenium Webdriver (Java) - 从 css 选择器中排除特定标签

python - 未绑定(bind)本地错误: local variable "tries" referenced before assignment

python - PyQt 打开另一个窗口

javascript - 滚动为电子表格

html - 如何防止表格在调整大小时溢出其封闭的 div?

python - FigureCanvasWxAgg 在 linux 的面板(或笔记本)中无法正确调整大小