2024-04-24 23:32:28 发布
网友
有了BeautifulSoul和Python,我想find_all所有的tr项都匹配一个给定的类属性,这个类属性包含多个类似这样的名称:
find_all
tr
<tr class="admin-bookings-table-row bookings-history-row paid ">
我试过几种方法来和那个班匹配。正则表达式,通配符,但我总是得到一个空列表。
有没有办法使用正则表达式、通配符或如何匹配这个类?
也有同样的问题here没有答案。
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>]
I want to find_all all tr items with a given class that contain multiple spaces.
多个空格实际上表示标记中的多个类。可以对具有多个类的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)
可以使用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
HTML类不能包含空格。此元素有多个类。
通过以下任一类进行搜索:
全部输出
多个空格实际上表示标记中的多个类。可以对具有多个类的
tr
标记进行筛选,如下所示:或者,使用lambda:
可以使用css selector来匹配许多类:
否则,也许这个答案也能帮助你: https://stackoverflow.com/a/46719501/6655211
相关问题 更多 >
编程相关推荐