首页 > 解决方案 > 如何使用 Python 从网站中提取逗号、句点或 colin 之前的所有文本

问题描述

从网站提取时,我试图将两个地址行拆分为 2 个不同的变量,但有些位置只有 1 个地址。我发现通常有逗号、colin 或句点分隔两条地址线。我正在提取所有位置,并且该网站是具有两个地址行的位置的示例。在这种情况下,地址 1 将是 2 Hemlock Rd。第二个地址是 PO Box 904。在其他没有 2 个地址的情况下,地址 2 应该为空。

这是网站:https ://www.winmar.ca/find-a-location/#267

这是 Python 代码,以及网站的 html。

location_address1 = soup.select_one(f"[data-id='{num}'] .heading:contains('Address') + p").contents[0].strip()
location_address2 = ','.join(location_address1.split(',|.|:')[1:]) 
<p>
2 Hemlock Rd. PO Box 904
<br>
Corner Brook, NL
<br>
A2H 6J2
</p>

标签: pythonhtmlpython-3.xweb-scraping

解决方案


您需要在这里选择更好的 HTML 是解决方案。我使用了 CSS 选择器,因为它更准确;因为 beautifoulSoup 上没有 xPath。在获得将对象转换为文本所需的一切之后,然后解决可用内容;然后在这里我们拆分行并删除换行符以获得更好的缩进。

注意:这已经过测试并且可以正确运行。

运行代码:

import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.winmar.ca/find-a-location/#267")

soup = BeautifulSoup(page.content, 'html.parser')

address = soup.select('#box-309 > div:nth-child(2) > p:nth-child(5)')

text = address[0].get_text()
print(text)

输出:

 358 Keltic Drive Sydney River ,NS B1R 1V7

推荐阅读