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

能否用Selenium点击预言机表格Next按钮?元素查找返回NoneType

问题:如何用Selenium点击翻页按钮查看预言机表格?

我想通过点击按钮翻页查看展示预言机答案的表格,确认能用Selenium实现点击该按钮吗?我已经确认XPath是正确的,但尝试两种元素查找方式都返回NoneType,相关代码如下:

from selenium import webdriver
from bs4 import BeautifulSoup
import time
import pyautogui

# 初始化Chrome浏览器驱动
driver = webdriver.Chrome()

# 访问质押页面
driver.get('https://staking.chain.link/')

# 等待页面加载
time.sleep(15)

# 查找“Next”按钮
next_button = driver.find_element_by_xpath('/html/body/div[1]/main/div/div[3]/div[3]/button[2]')

# 点击按钮加载下10条结果
next_button.click()

我还尝试了以下代码:

next_button = driver.find_element_by_class('button_secondary__WYcyn paragraph-100')

解决方法

  • 放弃绝对XPath:像/html/body/...这种绝对路径容错率极低,页面结构稍有变动就会失效。改用相对定位方式,比如按按钮文本、类名组合定位:

    from selenium.webdriver.common.by import By
    
    # 通过按钮文本定位
    next_button = driver.find_element(By.XPATH, "//button[contains(text(), 'Next')]")
    # 多类名组合需用CSS选择器(Selenium的CLASS_NAME仅支持单个类名)
    next_button = driver.find_element(By.CSS_SELECTOR, "button.button_secondary__WYcyn.paragraph-100")
    
  • 替换强制等待为显式等待:time.sleep(15)是固定时长等待,可能元素还未加载完成就执行查找。改用显式等待,直到元素可点击再操作:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # 最长等待20秒,直到按钮可点击
    next_button = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button.button_secondary__WYcyn.paragraph-100"))
    )
    next_button.click()
    
  • 检查元素是否在iframe内:如果按钮嵌套在iframe中,必须先切换到iframe才能查找元素:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # 定位并切换到目标iframe(替换为实际iframe的定位器)
    iframe = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.XPATH, "//iframe[@id='xxx']"))
    )
    driver.switch_to.frame(iframe)
    
    # 查找并点击按钮
    next_button = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button.button_secondary__WYcyn.paragraph-100"))
    )
    next_button.click()
    
    # 操作完成后切回主页面
    driver.switch_to.default_content()
    
  • 元素被遮挡时用JS点击:若按钮存在但被其他元素遮挡无法点击,用JavaScript强制触发点击:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    next_button = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "button.button_secondary__WYcyn.paragraph-100"))
    )
    driver.execute_script("arguments[0].click();", next_button)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:20:13