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

如何用Beautiful Soup抓取HTML中<br>标签后的内容?

用Beautiful Soup获取
标签后的内容解决方案

嘿,我来帮你搞定这个问题!你遇到的情况应该是直接获取div的文本或子节点时,把原价和折扣价都包含进去了对吧?下面给你几种靠谱的实现方法:

方法一:通过<br>标签的next_sibling获取

这种方法最直接,找到<br>标签后,取它的下一个兄弟节点就是我们要的折扣价,记得用strip()去掉多余的空白:

from bs4 import BeautifulSoup

# 你的HTML内容
html = '''<div class="col search_price discounted responsive_secondrow"> <span style="color: #888888;"><strike>CDN$ 2.29</strike></span> <br>CDN$ 1.48 </div>'''

# 解析HTML
soup = BeautifulSoup(html, 'html.parser')
# 定位目标div
target_div = soup.find('div', class_='col search_price discounted responsive_secondrow')

# 获取<br>后的内容
discounted_price = target_div.find('br').next_sibling.strip()
print(discounted_price)  # 输出: CDN$ 1.48

方法二:提取所有清理后的文本节点,取最后一个

如果页面结构稳定,折扣价总是最后一段有效文本,可以先提取div里所有去除空白的文本节点,再取最后一个:

from bs4 import BeautifulSoup

html = '''<div class="col search_price discounted responsive_secondrow"> <span style="color: #888888;"><strike>CDN$ 2.29</strike></span> <br>CDN$ 1.48 </div>'''
soup = BeautifulSoup(html, 'html.parser')
target_div = soup.find('div', class_='col search_price discounted responsive_secondrow')

# 获取所有清理后的文本节点
cleaned_texts = [text.strip() for text in target_div.stripped_strings]
# 取最后一个就是折扣价
discounted_price = cleaned_texts[-1]
print(discounted_price)  # 输出: CDN$ 1.48

方法三:过滤文本节点,筛选有效内容

这种方法更灵活,先获取div里所有文本节点,过滤掉空白内容后取最后一项:

from bs4 import BeautifulSoup

html = '''<div class="col search_price discounted responsive_secondrow"> <span style="color: #888888;"><strike>CDN$ 2.29</strike></span> <br>CDN$ 1.48 </div>'''
soup = BeautifulSoup(html, 'html.parser')
target_div = soup.find('div', class_='col search_price discounted responsive_secondrow')

# 获取所有文本节点并过滤空白
all_valid_text = [t.strip() for t in target_div.find_all(text=True) if t.strip()]
discounted_price = all_valid_text[-1]
print(discounted_price)  # 输出: CDN$ 1.48

这些方法都能精准拿到你要的<br>之后的内容,选哪种都可以,看你觉得哪种更符合自己的代码习惯~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:12:47