python - 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 标签中。
解决方案
对于此任务,您可以使用.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>
推荐阅读
- javascript - 在 JavaScript 中将乘法表值打印到文本框中
- list - 是否有可能通过带有所选值(如 alt、与 HTML 元素一起使用的标题)的 java 列表选择组合框元素传递附加字符串?
- javascript - 是否可以将多个导入设置为数组?
- c++ - 如何在 C++ 中转置 cv::SparseMat
- php - MYSQL 中的这个日期比较可以工作吗?
- jquery - jQuery点击附加类
- c++ - 转发声明的枚举,.h 中的默认值
- laravel - 如何在 Laravel 5.6 中禁用注册新用户
- sql - 如何获得一行中的最大值以及所有列的名称以获得相等的值
- php - 使用 PHP 正则表达式从字符串中提取年份