You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python+BeautifulSoup提取被br标签分隔的地址信息?

提取被<br>分隔的地址信息:BeautifulSoup解决方案

看起来你已经找对了方向,只是需要过滤掉冗余的空节点和无效值。这里有两种高效的实现方式,能帮你得到干净的目标文本:

你的目标HTML结构

<div class="item-listing"> 
  <h4><a href="/alps/" target="_blank">AK</a></h4> 
  5200 A St Ste 102<br> 
  Anchorage, AK 99518<br> 
  Phone: (907) 563-9333 <br> 
  <ul class="list-items" style="margin-top: 5px;"> 
    <li style="padding: 3px; background: #efefef; border-radius: 4px;"><img src="/images/icon-rec.png" style="height: 24px; width: 24px;" alt="Rl" data-toggle="tooltip" data-placement="top" title="Sales"></li> 
  </ul> 
  <a style="margin-right: 10px;" href="http://www.alps.com/?" target="_blank">Website</a> 
  <a href="/al/anchorage/" target="_blank">Profile</a> 
</div>

你的尝试分析

第一种方法只拿到第一行地址,是因为next_sibling仅获取了h4之后的第一个节点;第二种方法拿到了所有兄弟节点,但包含大量空字符串和None,需要进一步过滤。

解决方案1:精准过滤next_siblings中的有效文本

直接遍历h4的兄弟节点,筛选出字符串类型的有效内容,遇到无关标签就停止遍历:

from bs4 import BeautifulSoup, NavigableString

content = """上述HTML内容"""
soup = BeautifulSoup(content, "lxml")

for item in soup.select(".item-listing"):
    h4 = item.select_one("h4")
    addr_parts = []
    for sibling in h4.next_siblings:
        # 遇到ul或a标签就停止,避免处理无关内容
        if sibling.name in ["ul", "a"]:
            break
        # 只保留非空的字符串节点
        if isinstance(sibling, NavigableString):
            stripped_text = sibling.strip()
            if stripped_text:
                addr_parts.append(stripped_text)
    full_addr = " ".join(addr_parts)
    print(full_addr)

输出结果:

5200 A St Ste 102 Anchorage, AK 99518 Phone: (907) 563-9333

解决方案2:提取父元素文本并切片过滤

如果HTML结构稳定,也可以一次性提取父元素的所有文本,再通过切片排除无关内容,代码更简洁:

soup = BeautifulSoup(content, "lxml")

for item in soup.select(".item-listing"):
    # 按换行分割所有文本,清理空白后过滤空行
    all_lines = [line.strip() for line in item.get_text(separator="\n").split("\n") if line.strip()]
    # 排除h4的文本(第一个元素)和最后两个链接文本
    addr_lines = all_lines[1:-2]
    full_addr = " ".join(addr_lines)
    print(full_addr)

两种方法的优势

  • 第一种方法精准控制遍历范围,避免处理多余节点,适合结构复杂的HTML;
  • 第二种方法代码简洁易维护,适合结构固定的场景。

内容的提问来源于stack exchange,提问作者SIM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:41:23