簡體   English   中英

美麗的湯什么也沒有回報

[英]Beautiful soup returns nothing

這是HTML代碼:

<div xmlns="" style="box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;">42263 - Unencrypted Telnet Server</div>

我正在嘗試打印42263 - Unencrypted Telnet Server使用Beautiful Soup的42263 - Unencrypted Telnet Server但是輸出為空元素,即[]

這是我的Python代碼:

from bs4 import BeautifulSoup
import csv
import urllib.request as urllib2

with open(r"C:\Users\sourabhk076\Documents\CBS_1.html") as fp:
    soup = BeautifulSoup(fp.read(), 'html.parser')

divs = soup.find_all('div', attrs={'background':'#fdc431'})

print(divs)

正則表達式的解決方案:

from bs4 import BeautifulSoup
import re

with open(r"C:\Users\sourabhk076\Documents\CBS_1.html") as fp:
    soup = BeautifulSoup(fp.read(), 'html.parser')

讓我們找到與以下正則表達式匹配的div: background:\\s*#fdc431; \\s匹配單個Unicode空格字符。 我假設可以有0個或多個空格,所以我添加了*修飾符以匹配前面的RE的0個或多個重復。 您有時可以在這里閱讀有關正則表達式的更多信息。 我也建議您使用此在線正則表達式測試器

div = soup.find('div', attrs={'style': re.compile(r'background:\s*#fdc431;')})

但是,這等效於:

div = soup.find('div', style=re.compile(r'background:\s*#fdc431;'))

您可以在BeautifulSoup的官方文檔中閱讀有關內容

值得一讀的是有關可以為find和其他類似方法提供的篩選器類型的部分。

您可以提供字符串,正則表達式,列表, True或函數,如Keyur Potdar在其anwser中所示。

假設div存在,我們可以通過以下方式獲取其文本:

>>> div.text
'42263 - Unencrypted Telnet Server'

background不是div標簽的屬性。 div標簽的屬性是:

{'xmlns': '', 'style': 'box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;'}

因此,要么必須使用

soup.find_all('div', attrs={'style': 'box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;'}

或者,您可以使用lambda函數檢查background: #fdc431是否在style屬性值中,如下所示:

soup = BeautifulSoup('<div xmlns="" style="box-sizing: border-box; width: 100%; margin: 0 0 10px 0; padding: 5px 10px; background: #fdc431; font-weight: bold; font-size: 14px; line-height: 20px; color: #fff;">42263 - Unencrypted Telnet Server</div>', 'html.parser')
print(soup.find(lambda t: t.name == 'div' and 'background: #fdc431' in t['style']).text)
# 42263 - Unencrypted Telnet Server

或者,您可以使用RegEx,如Jatimir在他的答案中所示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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