2017-10-12 132 views
-1

隨着BeautifulSoul和Python類,我想find_all所有tr項目匹配包含多個名字,像一個給定的類屬性這一個:BeautifulSoup與空間

<tr class="admin-bookings-table-row bookings-history-row paid "> 

我曾嘗試多種方法來匹配類。正則表達式,通配符,但我總是得到一個空的列表。

有什麼方法可以使用正則表達式,通配符或如何匹配這個類?

發佈了相同的問題here沒有答案。

+6

爲了記錄,一個類不能有空格。這個元素有多個類。 – DeepSpace

回答

3

可以使用css selector匹配許多類:

from bs4 import BeautifulSoup as soup 
html = ''' 
<tr class="admin-bookings-table-row bookings-history-row paid "></tr> 
<tr class="admin-bookings-table-row nope paid "></tr> 
''' 
soup = soup(html, 'lxml') 

res = soup.select('tr.admin-bookings-table-row.bookings-history-row.paid') 
print(res) 

>>> [<tr class="admin-bookings-table-row bookings-history-row paid "></tr>] 

否則,也許這個答案可以幫助你: https://stackoverflow.com/a/46719501/6655211

1

HTML類不能包含空格。這個元素有多個類。

通過這兩種類別的搜索工作:

from bs4 import BeautifulSoup 

html = '<tr id="history_row_938220" style="" class="admin-bookings-table-row bookings-history-row paid ">' 


soup = BeautifulSoup(html, 'html.parser') 

print(soup.find_all(attrs={'class': 'admin-bookings-table-row'})) 
print(soup.find_all(attrs={'class': 'bookings-history-row'})) 
print(soup.find_all(attrs={'class': 'paid'})) 

所有輸出

[<tr class="admin-bookings-table-row bookings-history-row paid " 
id="history_row_938220" style=""></tr>] 
+0

問題似乎是找到所有具有多個類的'tr'項目。我不確定這是否會發現。 –

+0

@BradSolomon我剛纔已經證明,使用*這三個類中的任何一個都可以找到這個元素,所以我不確定OP爲了得到一個空列表而做了什麼。 – DeepSpace

+0

這不是問題。 「我想查找包含多個空格的給定類的所有tr項目。」如果你有一個標籤'class =「paid」',你的'attrs'過濾器會返回它,即使它只有一個類。 –

1

我想find_all所有tr項與給定的類包含 多個空格。

多個空格實際上表示標籤內的多個類。您可以篩選tr標籤有多個類,像這樣:

html_doc = """ 
<html><head><title>a title here</title></head> 
<body> 
<tr class="admin-bookings-table-row bookings-history-row paid " id="link1">Elsie</tr>, 
<tr class="oneclass" id="link2">Lacie</tr> 
<tr class="tag1 tag2" id="link3">Tillie</tr> 
""" 
soup = BeautifulSoup(html_doc, 'html.parser') 
filt = [tag for tag in soup.find_all('tr') if len(tag.get('class')) > 1] 

filt # Only 2 of 3 tags returned--excludes tag with just 1 class 
# [<tr class="admin-bookings-table-row bookings-history-row paid " id="link1">Elsie</tr>, 
# <tr class="tag1 tag2" id="link3">Tillie</tr>] 

或者使用Lambda:

soup.find_all(lambda tag: tag.name=='tr' and len(tag.get('class')) > 1) 
+0

「與給定班級」不確定OP是否在尋找所有多個班級 – PRMoureu

+0

好吧,我明白你的意思了。 @RuBiCK,我誤解了嗎? –

+0

我希望能夠使用正則表達式和處理字符串:)在這種情況下,目標是通過「管理員預訂錶行排列預訂歷史行支付」找到,同時只有三個類 – RuBiCK