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

使用BeautifulSoup无法匹配含Job #的span标签,求解决方案

解决BeautifulSoup匹配含子标签的span标签失败问题

问题原因

目标<span>标签内部除了文本Job #,还包含一个空的<o:p></o:p>子标签。BeautifulSoup的string参数会进行精确匹配,只有当标签的直接文本内容完全等于目标字符串且无其他子标签时,才会返回匹配结果,所以直接用string="Job #"会返回None。

可行解决方案

1. 正则表达式模糊匹配

利用re.compile匹配包含目标文本的span标签:

from bs4 import BeautifulSoup
import re
text = "<tr>\n<td style=\"width:127.5pt;padding:3.75pt 0in 3.75pt 0in\" width=\"170\">\n<p class=\"MsoNormal\"><span style=\"font-size:11.0pt\">Job #<o:p></o:p></span></p>\n</td>\n<td style=\"padding:3.75pt 0in 3.75pt 3.75pt\">\n<p class=\"MsoNormal\"><strong><span style='font-size:11.0pt;font-family:\"Calibri\",sans-serif'>TEST-12311</span></strong><span style=\"font-size:11.0pt\"><o:p></o:p></span></p>\n</td>\n</tr>"
soup = BeautifulSoup(text,"html.parser")

# 使用正则匹配包含"Job #"的span
job_number = soup.find("span", text=re.compile(r"Job #"))
print(job_number)

2. Lambda表达式筛选

通过lambda函数判断标签文本是否包含目标内容:

job_number = soup.find("span", lambda tag: tag.string and "Job #" in tag.string)

如果需要精确匹配(忽略可能的空白字符),可以加上strip():

job_number = soup.find("span", lambda tag: tag.string and tag.string.strip() == "Job #")

3. 遍历筛选所有span标签

手动遍历所有span标签,逐一检查文本内容:

job_number = None
for span in soup.find_all("span"):
    if span.string and "Job #" in span.string:
        job_number = span
        break
print(job_number)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:17:29