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

Selenium获取链接列表后点击特定链接报错,求解决方法

Selenium点击特定链接报错问题解决

问题描述

编写了一段Selenium代码获取网站所有链接,尝试运行期间点击特定链接,预期调用click()跳转,但运行报错。

原代码

import selenium
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
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://www.python.org"

driver = webdriver.Chrome()
driver.get(url)
driver.minimize_window()

links = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//a")))

for link in links:
    href = link.get_attribute("href")
    if href is not None:
        print(href)
#
# go to link 0
#
link(0).click


driver.quit()

报错信息

Traceback (most recent call last):
  File "/media/joe-2/Ubuntu-Storage1/Exuma-Snoops/RGD-code/link-test-2.py", line 25, in <module>
    link(0).click
TypeError: 'WebElement' object is not callable

错误原因及修正方案

  • 错误1:错误引用列表元素
    循环中的link是links列表里的单个WebElement对象,不是列表,不能用link(0)这种函数调用的方式获取元素。要访问列表里的第一个链接,应该用links[0](列表索引语法)。

  • 错误2:未调用click方法
    click是WebElement的方法,必须加括号click()才能执行点击操作,只写click只是引用方法对象,不会触发点击行为。

修正后的代码片段

# ... 前面代码保持不变 ...

for link in links:
    href = link.get_attribute("href")
    if href is not None:
        print(href)
#
# go to link 0
#
links[0].click()  # 修正此处代码

driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:33:27