[英]Web scrape html lines based on background color?
我目前是 web 与 Python 刮擦的新手。 如图所示属于示例 HTML 代码。
<div class="bb-fl" style="background:Tomato;width:0.63px" title="10"></div>,
<div class="bb-fl" style="background:SkyBlue;width:0.19px" title="3"></div>,
<div class="bb-fl" style="background:Tomato;width:1.14px" title="18"></div>,
<div class="bb-fl" style="background:SkyBlue;width:0.19px" title="3"></div>,
<div class="bb-fl" style="background:Tomato;width:1.52px" title="24"></div>,
我想使用 beautifulsoup 来查找具有相同 class (bb-fl)的行并且仅返回具有以下内容的行: style="background:SkyBlue"
目前我已经弄清楚如何使用以下行返回所有具有“bb-fl”class 的 HTML 代码行。
soup.find_all('div',{'class':'bb-fl'})
您可以通过在此处使用一些正则表达式逻辑来实现:
from bs4 import BeautifulSoup
import re
html = """<div class="bb-fl" style="background:Tomato;width:0.63px" title="10"></div>,
<div class="bb-fl" style="background:SkyBlue;width:0.19px" title="3"></div>,
<div class="bb-fl" style="background:Tomato;width:1.14px" title="18"></div>,
<div class="bb-fl" style="background:SkyBlue;width:0.19px" title="3"></div>,
<div class="bb-fl" style="background:Tomato;width:1.52px" title="24"></div>,"""
soup = BeautifulSoup(html)
#Find all divs which style attribute contains ...
soup.find_all('div', style = re.compile("background:SkyBlue"))
结果:
[<div class="bb-fl" style="background:SkyBlue;width:0.19px" title="3"></div>,
<div class="bb-fl" style="background:SkyBlue;width:0.19px" title="3"></div>]
无论其他样式值可能是什么,它都会起作用。
您可以根据文档尝试以下操作
soup.find_all('div', attrs={'style':'background:SkyBlue'})
尝试这个
soup = BeautifulSoup(data, 'lxml')
bbfls = soup.find_all('div',{'class':'bb-fl'})
for bbfl in bbfls:
if "background:SkyBlue" in bbfl.attrs.get("style"):
print(bbfl.attrs)
如果你想在一行中试试这个:
soup = BeautifulSoup(data, 'lxml')
print([bbfl.attrs for bbfl in soup.find_all('div',{'class':'bb-fl'}) if "background:SkyBlue" in bbfl.attrs.get("style")])
Output
{'class': ['bb-fl'], 'style': 'background:SkyBlue;width:0.19px', 'title': '3'}
{'class': ['bb-fl'], 'style': 'background:SkyBlue;width:0.19px', 'title': '3'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.