2017-10-12 66 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