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

如何用Selenium Python在网页右键后选择第4位的‘另存为’选项?

解决Selenium右键菜单选择“另存为”的问题

原代码的核心问题

  • 模块拼写错误:Actionchains 需改为 ActionChains,keys 需改为 Keys
  • 缺少 Service 类的导入(需从 selenium.webdriver.chrome.service 导入)
  • 重复执行右键操作,导致菜单被触发两次
  • 箭头键仅按了2次,但目标“另存为”是第4位,需要按3次(默认选中第一个选项,下移3次才能到第4个)

方案一:修正右键菜单操作

如果坚持使用右键菜单的方式,修正后的代码如下:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service

webdriver_service = Service('c:\\Path\\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service)  # 注意Chrome首字母大写

url = "http://intranet.gs.com/equities/report"
driver.get(url)

# 选择页面body元素作为右键目标(比定位表格单元格更稳妥)
target_element = driver.find_element_by_tag_name("body")

actions = ActionChains(driver)
# 右键点击触发菜单
actions.context_click(target_element).perform()

# 连续按3次下箭头定位到第4个选项,再回车确认
for _ in range(3):
    actions.send_keys(Keys.ARROW_DOWN).perform()
actions.send_keys(Keys.ENTER).perform()

注意:这种方法依赖浏览器的右键菜单布局,若浏览器版本更新导致选项位置变化,代码会失效;且无法自动处理系统级的保存弹窗,需要手动选择路径和文件名,局限性较大。

方案二:直接保存页面源码(推荐)

更稳定可靠的方式是直接获取页面HTML源码并写入本地文件,完全无需依赖右键菜单:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

webdriver_service = Service('c:\\Path\\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service)

url = "http://intranet.gs.com/equities/report"
driver.get(url)

# 获取当前页面的完整HTML源码
page_source = driver.page_source

# 将源码写入本地HTML文件,可自定义保存路径和文件名
with open("saved_report.html", "w", encoding="utf-8") as f:
    f.write(page_source)

driver.quit()

这种方法不受浏览器菜单布局影响,能直接保存页面内容,还可灵活控制保存参数,稳定性和实用性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:57:57