【问题标题】:bs4 search a word in all attributes of a given tagbs4 在给定标签的所有属性中搜索一个单词
【发布时间】:2020-11-19 11:39:06
【问题描述】:

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

我有密码

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 标签中。

【问题讨论】:

    标签: python html selenium-webdriver web-scraping beautifulsoup


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这正是我所需要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2021-06-12
    相关资源
    最近更新 更多