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

Python Selenium操作已打开链接时触发AttributeError:'NoneType'对象无send_keys属性

Python Selenium操作已打开链接时触发AttributeError:'NoneType'对象无send_keys属性

嘿,我来帮你排查下问题所在!

首先,你碰到的这个AttributeError根源很明确:

open_link= search.click()

Selenium里的click()方法没有返回值,执行后会直接返回None,所以open_link就变成了None对象,之后调用open_link.send_keys()自然会报错——毕竟None根本没有send_keys这个方法呀!

而且就算你解决了这个问题,直接给元素发Ctrl+S也不是正确操作,因为Ctrl+S是浏览器的全局快捷键,应该作用在整个页面窗口上,而非某个特定元素。

下面给你两个可行的解决方案:


方案1:修正快捷键操作逻辑

  1. 去掉open_link的赋值,直接调用click()即可
  2. 点击链接后要等待新页面加载完成(用显式等待比隐式等待更可靠)
  3. 给页面的<body>元素发送快捷键,因为body是整个页面的容器,聚焦它就能触发浏览器的保存功能

修正后的代码如下:

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

driver = webdriver.Firefox()
driver.get("https://www.examtopics.com/discussions/comptia/94/")
driver.implicitly_wait(0.5)

# 找到目标链接并点击
search = driver.find_element(By.PARTIAL_LINK_TEXT, "CAS-004")
search.click()

# 等待新页面加载完成(等待body元素出现,确保页面已就绪)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body")))

# 给body元素发送保存快捷键
body = driver.find_element(By.TAG_NAME, "body")
body.send_keys(Keys.CONTROL + "s")
time.sleep(1)  # 等待系统保存弹窗弹出
body.send_keys(Keys.ENTER)

方案2:直接保存页面源码(更稳定)

模拟快捷键保存页面很容易受操作系统、浏览器设置干扰(比如默认保存路径、是否弹出确认框等),更可靠的方式是直接获取页面HTML源码,写入本地文件:

import selenium
import time
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.Firefox()
driver.get("https://www.examtopics.com/discussions/comptia/94/")
driver.implicitly_wait(0.5)

# 找到目标链接并点击
search = driver.find_element(By.PARTIAL_LINK_TEXT, "CAS-004")
search.click()

# 等待页面加载完成
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body")))

# 获取页面源码并保存到本地文件
page_source = driver.page_source
with open("CAS-004_page.html", "w", encoding="utf-8") as file:
    file.write(page_source)

print("页面已成功保存!")

这种方法不依赖浏览器快捷键,也不会被系统弹窗干扰,稳定性高很多。


备注:内容来源于stack exchange,提问作者Victor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:33:11