如何在类python中按特定子字符串查找带有类字符串的span

时间:2019-11-11 10:21:45

标签: python html date beautifulsoup calendar

我正在使用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>

我需要将{时间,标题,月份}合并为一个df。需要通过attr类中的子字符串“ calendar-date”进行选择。

我要使用

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

但是,这需要类具有确切的attrs。

我不知道如何编写代码。

3 个答案:

答案 0 :(得分:1)

尝试不带正则表达式的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)

答案 1 :(得分:0)

您可以获得所有span标签,然后将其过滤掉:

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

答案 2 :(得分:0)

您可以使用正则表达式。

例如:

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)

输出:

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