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

Selenium循环WebElement时内部元素重复获取问题求助

解决Selenium遍历WebElement时子元素重复获取第一个内容的问题

问题原因

你的代码存在两个关键错误,导致每次都拿到第一个span的内容:

  1. XPath语法错误://span[@class, "name"]里的逗号是错误写法,判断属性值应该用等号=,正确格式为@class="name"。
  2. 全局搜索而非上下文搜索://会从整个HTML文档根节点开始查找元素,哪怕是在某个profile元素上调用find_element,它依然会返回页面中第一个匹配的span,而非当前profile下的子元素。

解决方法

以下三种修正方案任选其一即可:

方案1:修正XPath为相对路径

在XPath开头添加.,表示从当前profile元素的上下文开始搜索子元素:

profiles = browser.find_elements(By.CLASS_NAME, 'profile')
for profile in profiles:
   print(profile.get_attribute('outerHTML'))
   print(profile.find_element(By.XPATH, './/span[@class="name"]').get_attribute('innerHTML'))
   print("Next item \n\n")

方案2:使用CLASS_NAME定位子元素

直接通过name类名在当前profile元素下查找子元素,无需编写XPath:

profiles = browser.find_elements(By.CLASS_NAME, 'profile')
for profile in profiles:
   print(profile.get_attribute('outerHTML'))
   print(profile.find_element(By.CLASS_NAME, 'name').get_attribute('innerHTML'))
   print("Next item \n\n")

方案3:使用CSS_SELECTOR定位子元素

CSS选择器语法更简洁,同样能精准定位当前元素下的子元素:

profiles = browser.find_elements(By.CLASS_NAME, 'profile')
for profile in profiles:
   print(profile.get_attribute('outerHTML'))
   print(profile.find_element(By.CSS_SELECTOR, '.name').get_attribute('innerHTML'))
   print("Next item \n\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:31:02