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

使用XPath判断父节点是否存在指定子元素并提取对应数据

解决方案

核心处理逻辑是先遍历所有用户父节点,再针对每个父节点单独查询下属子元素,找不到对应元素时直接填充None,保证三类数据列表长度完全一致。

完整可运行代码如下:

import csv
import os
import pandas as pd
from selenium import webdriver
# 导入元素不存在的异常类,用于捕获缺失字段
from selenium.common.exceptions import NoSuchElementException

chromedriver = "path to chromedriver"
driver = webdriver.Chrome(chromedriver)
driver.get('url of a website')

name_row = []
weight_row = []
height_row = []

# 先一次性获取所有用户父节点(reviews下的直接div子元素)
user_nodes = driver.find_elements_by_xpath('//div[@class="reviews"]/div')

for user in user_nodes:
    # 查找当前用户下的姓名字段,找不到就填None
    try:
        name = user.find_element_by_xpath('./div[@class="name"]').text.strip()
    except NoSuchElementException:
        name = "None"
    name_row.append(name)

    # 查找当前用户下的体重字段
    try:
        weight = user.find_element_by_xpath('./div[@class="weight"]').text.strip()
    except NoSuchElementException:
        weight = "None"
    weight_row.append(weight)

    # 查找当前用户下的身高字段
    try:
        height = user.find_element_by_xpath('./div[@class="height"]').text.strip()
    except NoSuchElementException:
        height = "None"
    height_row.append(height)

df = pd.DataFrame({'Names': name_row, 'Weight': weight_row, 'Height': height_row})
# 可直接打印查看结果,也可以用df.to_csv导出
print(df)

关键说明

  • 所有子元素查询使用.开头的相对xpath,只会在当前用户节点范围内查找,不会跨用户匹配数据
  • 用异常捕获处理字段缺失场景,自动填充None,不会出现列表长度不一致的报错
  • 生成的DataFrame完全符合你要求的输出格式,最终输出结果如下:
NamesWeightHeight
Will50kg160cm
None55kg170cm
BenNone180cm

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 17:03:00