首页 > 解决方案 > bs4 在给定标签的所有属性中搜索一个单词

问题描述

我正在开发一个网络爬虫来查找给定网站的价格标签。

我有一个代码

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>

我的代码仅检索价格关键字是否存在于类属性中,但在这种情况下,它存在于数据自动化属性中。

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

标签: pythonhtmlselenium-webdriverweb-scrapingbeautifulsoup

解决方案


对于此任务,您可以使用.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>

推荐阅读