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

如何在BeautifulSoup的CSS选择器中集成正则表达式匹配指定文本?

问题描述

我正在寻找一种在BeautifulSoup中使用正则表达式的解决方案,以查找包含文本“HO #”的元素,允许“HO”和“#”之间存在空格且忽略大小写。

目前我使用的代码如下:

check_ho_number3 = soup.select_one('td:-soup-contains("HO #")+ td')
print(check_ho_number3)

请问如何将我已有的正则表达式集成到soup.select_one()中?

我的正则表达式代码如下:

check_regex = re.compile("HO\s?#", re.IGNORECASE)
解决方案

BeautifulSoup的CSS选择器(包括select_one)并不支持直接在:soup-contains中使用正则表达式,你需要换一种思路实现需求:

方法一:结合find与正则匹配文本,再取相邻元素

先通过find方法找到文本匹配正则的td,再获取它的下一个兄弟td:

import re
from bs4 import BeautifulSoup

check_regex = re.compile(r"HO\s?#", re.IGNORECASE)

# 找到文本匹配正则的td元素
target_td = soup.find("td", text=check_regex)
if target_td:
    # 获取该td的下一个兄弟td
    check_ho_number3 = target_td.find_next_sibling("td")
    print(check_ho_number3)

方法二:先通过select获取所有td,再过滤匹配正则的元素

如果偏好使用select系列方法,可以先获取所有td元素,再用正则过滤出目标元素,最后取相邻的td:

check_regex = re.compile(r"HO\s?#", re.IGNORECASE)

# 筛选出文本匹配正则的td
target_tds = [td for td in soup.select("td") if check_regex.search(td.get_text(strip=True))]
if target_tds:
    check_ho_number3 = target_tds[0].find_next_sibling("td")
    print(check_ho_number3)

说明

:soup-contains是BeautifulSoup对CSS选择器的扩展,仅支持简单的文本包含匹配,无法直接集成正则。上述两种方法都是先定位到文本符合正则的元素,再完成后续的相邻元素获取,和你原代码的逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 23:54:52