簡體   English   中英

如何通過 class python 中的特定 substring 找到 class 字符串的跨度

[英]How to find span with class string by specific substring in the class python

我正在使用 Beautifulsoup 下載一些數據。 我提取代碼,它看起來像這樣。

<td><span class="calendar-date-2">11:50 PM </span></td>,
<tr><td>
<div title="ABC"></div>
</td></tr>
<span>SEP</span>

<td><span class="calendar-date-1">12:00 PM </span></td>,
<tr><td>
<div title="CDE"></div>
</td></tr>
<span>OCT</span>

<td><span class="calendar-date-3">12:10 PM </span></td>,
<tr><td>
<div title="FGH"></div>
</td></tr>
<span>NOV</span>

我需要將 {time, title, month} 放入一個 df 中。 這需要 select 由 class 屬性中的 substring “日歷日期”。

我想用

bs4.find_all('span',{class: XXX})

但這需要 class 具有確切的屬性。

我不知道如何編寫代碼。

嘗試不使用正則表達式的 css 選擇器。

from bs4 import BeautifulSoup

datahtml = """<td><span class="calendar-date-2">11:50 PM </span></td>,
<tr><td>
<div title="ABC"></div>
</td></tr>
<span>SEP</span>

<td><span class="calendar-date-1">12:00 PM </span></td>,
<tr><td>
<div title="CDE"></div>
</td></tr>
<span>OCT</span>

<td><span class="calendar-date-3">12:10 PM </span></td>,
<tr><td>
<div title="FGH"></div>
</td></tr>
<span>NOV</span>"""

soup = BeautifulSoup(datahtml, "html.parser")
for span in soup.select("[class^='calendar-date-']"):
    print(span.text)
    print(span.find_previous('td').find_next('div')['title'])
    print(span.find_next('span').text)

您可以獲取所有span標簽,然后將它們過濾掉:

spans = [s for s in bs4.find_all('span') if s.get('class', [''])[0].startswith('calendar-date')]

您可以使用正則表達式。

前任:

import re
from bs4 import BeautifulSoup

html = """<td><span class="calendar-date-2">11:50 PM </span></td>,
<tr><td>
<div title="ABC"></div>
</td></tr>
<span>SEP</span>

<td><span class="calendar-date-1">12:00 PM </span></td>,
<tr><td>
<div title="CDE"></div>
</td></tr>
<span>OCT</span>

<td><span class="calendar-date-3">12:10 PM </span></td>,
<tr><td>
<div title="FGH"></div>
</td></tr>
<span>NOV</span>"""

soup = BeautifulSoup(html, "html.parser")
for span in soup.find_all("span", class_=re.compile(r"^calendar\-date\-\d+")):
    print(span.text)
    print(span.find_previous('td').find_next('div')['title'])
    print(span.find_next('span').text)

Output:

11:50 PM 
ABC
SEP
12:00 PM 
CDE
OCT
12:10 PM 
FGH
NOV

暫無
暫無

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

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