基于BeautifulSoup抓取地址后,如何格式化拆分地址字段
地址拆分与格式化方案
你抓取到的地址文本是按换行分隔的结构,我们可以通过拆分文本行、映射字段的方式实现格式化:
步骤1:拆分并清理地址行
先将获取到的地址文本按换行符分割,过滤空行并清理每行的多余空白:
# 获取地址元素后执行 address_lines = [line.strip() for line in info.text.split('\n') if line.strip()]
以StoreID=1513为例,这一步会得到干净的地址列表:['Moor Street Station Queensway', 'Birmingham', 'West Midlands', 'B4 7UL', 'United Kingdom']
步骤2:映射字段并格式化输出
根据你需要的示例格式,直接按顺序映射字段后用|拼接:
if len(address_lines) == 5: detail_addr, city, region, postcode, country = address_lines formatted_addr = f"{detail_addr} | {region} | {city} | {postcode} | {country}" print(formatted_addr) else: print("地址格式异常,无法拆分")
完整修改代码
import requests from bs4 import BeautifulSoup l = "https://www.whsmith.co.uk/stores/details/?StoreID=" + "1513" html_text = requests.get(l).text soup = BeautifulSoup(html_text,'html.parser') info = soup.find('div', attrs={'class':'t-store-details__store-address'}) # 地址拆分与格式化逻辑 address_lines = [line.strip() for line in info.text.split('\n') if line.strip()] if len(address_lines) == 5: detail_addr, city, region, postcode, country = address_lines formatted_addr = f"{detail_addr} | {region} | {city} | {postcode} | {country}" print(formatted_addr) else: print("地址格式异常,无法拆分")
注意事项
- 该方案依赖网站地址行的固定顺序,若其他门店地址结构有变动,需调整字段映射逻辑
- 可进一步添加异常捕获逻辑,避免页面结构变更导致的程序报错
内容的提问来源于stack exchange,提问作者S L
相关产品推荐
相关产品推荐

