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

Python Selenium无法定位网页PDF下载按钮问题求助

问题描述

我想用Python的Selenium点击NFL官网赛事页面(https://www.nfl.com/games/49ers-at-seahawks-2022-reg-15)上标注为“Download Gamebook (pdf)”的按钮,但始终无法正确定位该按钮,尝试多种定位方式均报错。

尝试过的代码

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
import time

# 初始化浏览器并访问页面
driver = webdriver.Chrome()
driver.get("https://www.nfl.com/games/49ers-at-seahawks-2022-reg-15")

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

# 查找并点击按钮
# 其他尝试过的定位方式
#button = driver.find_element(By.XPATH, "//div[contains(text(), 'Download Game Book (PDF)')]" )
#button = driver.find_element(By.LINK_TEXT, "Download Game Book (PDF)" )
#button = driver.find_element(By.PARTIAL_LINK_TEXT, "Download Game Book (PDF)" )
#button = driver.find_element(By.CLASS_NAME, "css-text-901oao r-alignItems-1awozwy r-color-1khnkhu r-display-6koalj r-flexDirection-18u37iz r-fontFamily-1fdbu1n r-fontSize-1b43r93" )
#button = driver.find_element(By.XPATH, "//button[text(), 'Download Game Book (PDF)']" )

button = driver.find_element(By.ID, "gamecenter-cta-btns-container" )
button.click()

# 等待PDF下载
time.sleep(10)

# 打印当前URL
url = driver.current_url
print(url)

# 关闭浏览器
driver.quit()

报错信息

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="gamecenter-cta-btns-container"]"}

注释中的其他定位方式也返回类似的“找不到元素”错误,参考相关问题未解决。按钮的HTML结构显示其为包含“Download Game Book (PDF)”文本的可点击元素。


解决方案

关键问题分析

  1. 固定休眠time.sleep()不可靠,可能元素未加载完成就执行查找操作
  2. 部分定位语法错误:如By.CLASS_NAME不支持多class,XPATH的text()写法错误
  3. 未处理文本中的多余空格,导致文本匹配失败

修正后的代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化浏览器
driver = webdriver.Chrome()
driver.get("https://www.nfl.com/games/49ers-at-seahawks-2022-reg-15")

try:
    # 显式等待按钮可点击,最长等待15秒
    # 使用normalize-space处理文本中的空格/换行
    button = WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.XPATH, "//*[normalize-space(text())='Download Game Book (PDF)']"))
    )
    button.click()

    # 若点击后打开新窗口,切换到新窗口并打印URL
    WebDriverWait(driver, 10).until(lambda d: len(driver.window_handles) > 1)
    driver.switch_to.window(driver.window_handles[-1])
    print(driver.current_url)

finally:
    # 无论成功失败都关闭浏览器
    driver.quit()

额外说明

  • 显式等待:替代固定休眠,确保元素加载完成后再操作,提升稳定性
  • XPATH优化:normalize-space()消除文本中的多余空格、换行,避免匹配失败
  • 多class问题:By.CLASS_NAME仅支持单个class,若要用class定位,选一个唯一的单个class即可
  • 下载验证:若按钮直接触发下载而非打开新窗口,可通过检查本地下载目录的文件来确认操作成功

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:35:31