【问题标题】:Unable to separate two fields out of some messy html elements无法从一些杂乱的 html 元素中分离出两个字段
【发布时间】:2020-11-14 05:27:47
【问题描述】:

我正在尝试从 html 元素中获取邮政编码和城市。但是,我找不到任何方法来单独抓取它们。

<div class="profile-info__address" itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress">
            <img src="/Content/images/icons/location-pin.svg" class="icon-left">
            1000 Bruxelles<br>Rue de Laeken 160
        </div>

预期输出:

zipcode = 1000
city = Bruxelles

我试过了:

from bs4 import BeautifulSoup

html = """
<div class="profile-info__address" itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress">
            <img src="/Content/images/icons/location-pin.svg" class="icon-left">
            1000 Bruxelles<br>Rue de Laeken 160
        </div>
"""
soup = BeautifulSoup(html,"html.parser")
address_container = [item.string.strip() for item in soup.select_one("[itemprop='address']") if item.string]
print(address_container)

它产生:

['', '1000 Bruxelles', 'Rue de Laeken 160']

如何将两个字段与地址分开?

注意:您在输出中看到的前导空格可能并不总是存在。

【问题讨论】:

  • 邮编总是在城市名之前吗?

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

如果邮政地址(某种程度上)是统一的,并且邮政编码位于城市之前,您可以检查是否有任何字符串元素以数字(或一系列匹配的数字)开头邮政编码的长度)。

例如:

import re

from bs4 import BeautifulSoup

html = """
<div class="profile-info__address" itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress">
            <img src="/Content/images/icons/location-pin.svg" class="icon-left">
            1000 Bruxelles<br>Rue de Laeken 160
        </div>
"""

soup = BeautifulSoup(html, "html.parser").select_one("[itemprop='address']")
address_container = [item.string.strip() for item in soup if item.string]
filtered_address = [i for i in address_container if re.search(r"^\d+", i)]

for item in filtered_address:
    zip_code, city = item.split()
    print(f"Zip: {zip_code}")
    print(f"City: {city}")

输出:

Zip: 1000
City: Bruxelles

【讨论】:

  • 是的,这似乎是一个不错的选择。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 2021-05-15
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多