簡體   English   中英

Web 根據背景顏色刮 html 線條?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM