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

如何在Selenium中获取隐藏元素的值?网页product_id获取失败求助

解决获取product_id失败的问题

问题分析

原代码尝试通过text获取目标元素内容,但可能存在以下问题:

  • 目标元素的product_id并非存储在文本节点中,而是在自定义属性里(比如data-product-id)
  • 元素处于隐藏状态,直接获取text返回空值
  • 隐式等待未确保元素完全加载完成

修正方案

方案1:获取元素的属性值

查看页面DOM结构后发现,该product__id hide元素的data-product-id属性存储了目标值,因此修改代码获取该属性:

from selenium import webdriver

url = 'https://beyours.vn/products/mia-circle-mirror-white'
driver = webdriver.Chrome()  # 需确保ChromeDriver已配置环境
driver.get(url) 
driver.implicitly_wait(10)

# 获取data-product-id属性值
sku = driver.find_element_by_xpath('//div[@class="product__id hide"]').get_attribute('data-product-id')
print(sku)  # 输出:1052656577

driver.quit()

方案2:使用显式等待确保元素加载

如果隐式等待不够可靠,改用显式等待等待元素存在:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'https://beyours.vn/products/mia-circle-mirror-white'
driver = webdriver.Chrome()
driver.get(url)

# 显式等待元素存在,最长等待10秒
product_element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//div[@class="product__id hide"]'))
)
sku = product_element.get_attribute('data-product-id')
print(sku)

driver.quit()

方案3:获取隐藏元素的文本内容

如果目标值确实在元素文本中但被隐藏,可通过textContent属性获取:

sku = driver.find_element_by_xpath('//div[@class="product__id hide"]').get_attribute('textContent').strip()

关键说明

  • 避免使用find_elements_by_xpath后取索引[0],直接用find_element_by_xpath更简洁,若元素不存在会直接抛出异常便于排查
  • 优先检查元素的属性而非仅文本,很多电商网站会将产品ID存储在自定义属性中
  • 显式等待比隐式等待更灵活,能针对特定元素设置等待条件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:10:17