如何用Python Selenium自动化右键另存为下载CSV文件?
用Python Selenium实现右键另存为CSV的自动化方案
完全可以用Python Selenium实现这个需求,下面提供两种可行方案,其中第二种更稳定可靠:
方案一:用ActionChains模拟右键操作(依赖浏览器菜单,兼容性稍差)
这种方法模拟人工右键点击、选择“另存为”的操作,但要注意Selenium无法直接控制系统级的保存对话框,需要提前配置浏览器默认下载路径并关闭弹窗提示:
步骤:
- 配置Chrome浏览器的下载设置,指定默认路径,自动完成下载
- 定位到目标导出链接
- 用ActionChains执行右键点击,再模拟键盘选择“另存为”(或直接触发下载选项)
代码示例:
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys # 配置Chrome下载设置 chrome_options = Options() download_path = "/your/download/path" chrome_options.add_experimental_option("prefs", { "download.default_directory": download_path, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": True }) driver = webdriver.Chrome(options=chrome_options) driver.get("https://www.who.int/data/gho/data/indicators/indicator-details/GHO/proportion-of-population-below-the-international-poverty-line-of-us$1-90-per-day-(-)") # 切换到数据标签页(根据页面实际元素调整定位方式) driver.find_element(By.LINK_TEXT, "Data").click() # 定位到导出CSV的链接元素 export_link = driver.find_element(By.PARTIAL_LINK_TEXT, "EXPORT DATA in CSV format") # 用ActionChains右键点击链接 actions = ActionChains(driver) actions.context_click(export_link).perform() # 模拟键盘按键选择“另存为”(不同浏览器/系统的菜单选项位置可能不同,需自行调整箭头次数) actions.send_keys(Keys.ARROW_DOWN * 3).send_keys(Keys.ENTER).perform() # 等待下载完成后关闭浏览器 driver.quit()
方案二:直接获取链接地址下载(更稳定推荐)
这种方法跳过右键操作,直接提取导出链接的href属性,用requests库下载文件,避免了系统弹窗的兼容性问题:
步骤:
- 打开目标页面,切换到数据标签页
- 定位导出链接并获取其
href值 - 用
requests发送请求下载到指定路径
代码示例:
from selenium import webdriver from selenium.webdriver.common.by import By import requests driver = webdriver.Chrome() driver.get("https://www.who.int/data/gho/data/indicators/indicator-details/GHO/proportion-of-population-below-the-international-poverty-line-of-us$1-90-per-day-(-)") # 切换到数据标签页 driver.find_element(By.LINK_TEXT, "Data").click() # 获取导出CSV的链接地址 export_url = driver.find_element(By.PARTIAL_LINK_TEXT, "EXPORT DATA in CSV format").get_attribute("href") # 关闭Selenium浏览器(不再需要) driver.quit() # 用requests下载文件(若网站需要会话验证,可传递Selenium的Cookies) save_path = "/your/save/path/poverty_data.csv" response = requests.get(export_url, allow_redirects=True) with open(save_path, "wb") as f: f.write(response.content) print(f"文件已保存到:{save_path}")
补充:会话验证处理
如果网站需要保持登录会话才能下载,可将Selenium的Cookies传递给requests:
# 在关闭浏览器前获取Cookies cookies = driver.get_cookies() session = requests.Session() for cookie in cookies: session.cookies.set(cookie['name'], cookie['value']) # 使用session发送请求 response = session.get(export_url, allow_redirects=True)
内容的提问来源于stack exchange,提问作者Patrick El Zaybak
相关产品推荐
相关产品推荐

