BeautifulSoup和类空间

RuB*_*iCK 2 python beautifulsoup

使用BeautifulSoul和Python,我希望find_all所有tr匹配给定类属性的项目包含多个名称,如下所示:

<tr class="admin-bookings-table-row bookings-history-row  paid   ">
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几种匹配该类的方法.正则表达式,通配符,但我总是得到一个空列表.

有没有办法使用正则表达式,通配符或如何匹配此类?

还有就是贴了同样的问题在这里没有答案.

PRM*_*reu 8

你可以使用css选择器来匹配许多类:

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>]
Run Code Online (Sandbox Code Playgroud)

否则,也许这个答案也可以帮到你:https: //stackoverflow.com/a/46719501/6655211


Dee*_*ace 6

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'}))
Run Code Online (Sandbox Code Playgroud)

所有输出

[<tr class="admin-bookings-table-row bookings-history-row paid " 
 id="history_row_938220" style=""></tr>]
Run Code Online (Sandbox Code Playgroud)