python - 如何使用 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>
解决方案
您需要在这里选择更好的 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
推荐阅读
- xamarin - Xamarin 窗体 UWP 应用程序在窗口调整大小后不会调整元素大小
- node.js - Axios 和 Oauth1.0 - '状态:400,错误请求'
- blazor - 通知 EditContext 该字段已更改以进行 Blazor 验证
- javascript - 如何防止传播运算符保持原始参考?
- java - 主线程上的 Android 处理程序使应用程序崩溃
- python - Django url re_path 无法重定向到正确的视图
- java - 如何基于 SftpRemoteFileTemplate 将 MessageHandler 集成到 SFTP 场景中?
- javascript - Adobe Acrobat - pdf-document - Javascript getpagerotation 总是返回 0
- json - 从 JSON 文件中读取数据并将其作为 Post 请求发送
- javascript - 在 div 之外单击时关闭 div