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

使用Python BeautifulSoup+XPath提取tspan标签文本失败,求助

问题分析与解决方案

核心原因

你用requests.get()获取的是页面静态HTML代码,但目标tspan标签(包含$3.7200的元素)是通过JavaScript动态渲染生成的,静态内容里根本不存在这个标签,所以XPath查询返回空列表。

解决方案

方案一:用Selenium渲染动态页面

Selenium可以模拟浏览器加载页面并执行JS,能获取到完整的渲染后内容。

步骤:

  1. 安装依赖:
pip install selenium
  1. 下载对应Chrome版本的ChromeDriver,将其放在系统PATH目录,或者在代码中指定路径。

代码示例:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

url = "https://www.findchips.com/detail/TS63Y502KR10/2516-Vishay%20Intertechnologies?quantity=1"

# 配置Chrome选项,无头模式不弹出浏览器窗口
chrome_options = Options()
chrome_options.add_argument('--headless=new')
chrome_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36')

# 初始化浏览器驱动
driver = webdriver.Chrome(options=chrome_options)
driver.get(url)

# 等待页面动态内容加载完成(可根据实际情况调整等待时间)
driver.implicitly_wait(5)

# 查找目标tspan标签
target_element = driver.find_element(By.XPATH, '//tspan[@class="point-info-number large"]')
print(target_element.text)

# 关闭浏览器
driver.quit()

方案二:直接调用数据接口(更高效)

打开浏览器开发者工具(F12),切换到Network标签,刷新页面后筛选XHR请求,找到返回价格数据的API接口,直接用requests请求该接口获取数据,不需要渲染整个页面。

示例代码(接口需以实际抓包结果为准):

import requests

api_url = "https://www.findchips.com/api/price/TS63Y502KR10"
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
    'Referer': 'https://www.findchips.com/detail/TS63Y502KR10/2516-Vishay%20Intertechnologies?quantity=1'
}

response = requests.get(api_url, headers=headers)
data = response.json()
# 从返回的JSON中提取价格字段,具体字段以实际接口返回为准
print(data['price'])

额外优化建议

  • 你的代码中同时导入了lxml.etree和lxml.html,属于冗余导入,保留lxml.etree即可。
  • 若坚持用BeautifulSoup结合lxml,需确保页面静态内容包含目标元素,否则此方式无法解决动态加载问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:05:28