如何使用Python BeautifulSoup将<br>分隔的项存储到单独的数组中?

2024-09-24 22:20:16 发布

您现在位置:Python中文网/ 问答频道 /正文

试图搜集攀岩馆的数据。我用的是美肌。 我想存储健身房名称、位置、电话号码、链接和描述的数组

以下是示例html:

div class="city">Alberta</div>
<p><b>Camp He Ho Ha Climbing Gym</b><br>
Seba Beach, Alberta, TOE 2BO Canada<br>
(780) 429-3277<br>
<a rel='nofollow' target='_blank' href='http://camphehoha.com/summer-camp/camp-life/'>Camp He Ho Ha Climbing Gym</a><br>
<span class='rt'></span> The Summit is Camp He Ho Ha's 40' climbing gym and ropes course. Facility is available for rent, with safety equipment, orientation to the course and staffing provided.</p>
<div class="city">Calgary</div>
<p><b>Bolder Climbing Community</b><br>
5508 1st Street SE, Calgary, Alberta, Canada<br>
403 988-8140<br>
<a rel='nofollow' target='_blank' href='http://www.bolderclimbing.com/'>Bolder Climbing Community</a><br>
<span class='rt'></span> Calgary's first bouldering specific climbing centre.</p>

我可以很容易地在每个攀岩馆之间移动,因为它们被<p>隔开,但是我感兴趣的单个项目被<br>隔开。如何将这些项存储到单独的数组中


Tags: brdivcity数组classhegymspan
1条回答
网友
1楼 · 发布于 2024-09-24 22:20:16

你可以这样做。基本上,找到<br>标记,然后找到它前面的内容

html = '''div class="city">Alberta</div>
<p><b>Camp He Ho Ha Climbing Gym</b><br>
Seba Beach, Alberta, TOE 2BO Canada<br>
(780) 429-3277<br>
<a rel='nofollow' target='_blank' href='http://camphehoha.com/summer-camp/camp-life/'>Camp He Ho Ha Climbing Gym</a><br>
<span class='rt'></span> The Summit is Camp He Ho Ha's 40' climbing gym and ropes course. Facility is available for rent, with safety equipment, orientation to the course and staffing provided.</p>
<div class="city">Calgary</div>
<p><b>Bolder Climbing Community</b><br>
5508 1st Street SE, Calgary, Alberta, Canada<br>
403 988-8140<br>
<a rel='nofollow' target='_blank' href='http://www.bolderclimbing.com/'>Bolder Climbing Community</a><br>
<span class='rt'></span> Calgary's first bouldering specific climbing centre.</p>'''

from bs4 import BeautifulSoup


soup = BeautifulSoup(html, 'html.parser')
final_content = []
ps = soup.find_all('p')
for p in ps:
    content = []
    breaks = p.find_all('br')
    for br in breaks:
        try:
            b = br.previousSibling.strip()
            content.append(b)
        except:
            continue
    final_content.append(content)

输出:

print (final_content)
[['Seba Beach, Alberta, TOE 2BO Canada', '(780) 429-3277'], ['5508 1st Street SE, Calgary, Alberta, Canada', '403 988-8140']]

相关问题 更多 >