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

Python Selenium执行JavaScript能否获取元素href属性列表?

实现方式说明

两种方案都可以满足需求,具体实现如下:


方法1:直接调用JS脚本

Selenium自带的execute_script()方法可以直接在当前页面上下文执行JS代码,和你在浏览器控制台运行的逻辑完全一致,写法更简洁高效:

# 提前初始化好Selenium的driver对象,示例用Chrome:
# from selenium import webdriver
# driver = webdriver.Chrome()

# 直接复用你写的JS代码,末尾加return返回结果即可
js_script = """
var elements = document.getElementsByClassName('example');
elements = [...elements].map(el => el.children[0].children[0].getAttribute('href').toString());
return elements;
"""
href_list = driver.execute_script(js_script)
# 直接拿到需要的href列表
print(href_list)

注意:JS代码末尾必须加return语句,否则execute_script()默认返回None


方法2:使用Selenium内置函数实现

如果你不想写JS代码,也可以用Selenium原生的元素定位、属性获取接口实现相同逻辑,方便做更细致的异常处理:

from selenium.webdriver.common.by import By

# 先获取所有class为example的元素
example_elements = driver.find_elements(By.CLASS_NAME, "example")
href_list = []
for el in example_elements:
    # 匹配当前元素的第一个孙节点
    grandchild = el.find_elements(By.XPATH, "./child::*[1]/child::*[1]")
    # 兼容元素不存在的场景,避免报错
    if grandchild:
        href = grandchild[0].get_attribute("href")
        if href:
            href_list.append(str(href))

两种方案对比:

  • 直接执行JS的运行速度更快,不会因为页面元素中途动态变更导致获取失败,代码量更少
  • 原生Selenium写法纯用Python语法,适合需要对每个元素做定制化校验的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:27:02