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

如何使用BeautifulSoup提取指定HTML标签内文本,获取西门子招聘页Req ID

具体实现方案

你需要通过find_all()的attrs参数指定要匹配的标签属性,完整可运行代码如下:

from bs4 import BeautifulSoup as BS
import urllib.request as ur

with ur.urlopen(f'https://jobs.siemens.com/jobs?page=1&sortBy=relevance&limit=100') as response:
    html = response.read()
    soup = BS(html, 'html.parser')
    
    # 匹配所有带指定属性的span标签
    span_tags = soup.find_all("span", attrs={"_ngcontent-blo-c163": ""})
    
    for tag in span_tags:
        content = tag.get_text(strip=True)
        # 过滤出纯数字格式的Req Id,找到第一个就输出退出
        if content.isdigit():
            print(content)
            break

补充说明

  • 推荐用tag.get_text(strip=True)代替tag.string提取文本,可以自动过滤多余空白、换行符,兼容性更好
  • 如果后续前端迭代导致_ngcontent-blo-c163属性值变化(Angular框架的这类自动生成属性经常会更新),可以换用文本特征匹配:先定位包含「Req ID」字样的元素,再取相邻的数字内容,稳定性更高
  • 若请求返回403错误,可添加User-Agent请求头模拟浏览器访问,示例如下:
from bs4 import BeautifulSoup as BS
import urllib.request as ur

# 构造带请求头的请求对象
req = ur.Request(
    url='https://jobs.siemens.com/jobs?page=1&sortBy=relevance&limit=100',
    headers={
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }
)

with ur.urlopen(req) as response:
    html = response.read()
    soup = BS(html, 'html.parser')
    
    span_tags = soup.find_all("span", attrs={"_ngcontent-blo-c163": ""})
    for tag in span_tags:
        content = tag.get_text(strip=True)
        if content.isdigit():
            print(content)
            break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 11:06:05