使用Python Selenium指定目录下载图片:登录网站后下载失败求助
解决Selenium指定下载目录时目标网站图片下载失败的问题
我用Python的Selenium(配合undetected_chromedriver)尝试将图片下载到指定目录,代码在下载示例图片时正常,但登录目标网站后下载图片会提示“Error Failed to download”,不指定下载目录时则能正常下载。以下是我的代码:
import undetected_chromedriver as uc from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains import pyautogui from time import sleep chrome_options = uc.ChromeOptions() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") # Specify the download directory prefs = { "download.default_directory": "C:/Users/ExampleUser/Documents/ExampleFolder/", "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": False } chrome_options.add_experimental_option("prefs", prefs) # Create the webdriver instance with the modified options driver = uc.Chrome(options=chrome_options) #This is where I have used selenium to login to the website here #havent posted the code to login # Open the image page driver.get('https://www.simplilearn.com/ice9/free_resources_article_thumb/what_is_image_Processing.jpg') #This is just a random image, not the image on the website sleep(3) # Perform a right-click on the image image_element = driver.find_element(By.XPATH, '/html/body/img') sleep(3) action_chains = ActionChains(driver) action_chains.context_click(image_element).perform() sleep(3) # Press the "V" key to select the "Save Image As" option pyautogui.press('v') sleep(3) # Press the Enter key to confirm the Save Image dialog pyautogui.press('enter') driver.quit()
问题原因
指定下载目录时,Chrome的安全策略或目标网站的下载限制(如防盗链、权限校验)会拦截下载请求;同时依赖pyautogui模拟右键保存的方式稳定性差,易受浏览器窗口状态影响。
解决方案一:直接通过HTTP请求下载(推荐)
绕过Chrome下载对话框,利用登录后的Cookie直接请求图片资源并保存,不受浏览器设置限制,稳定性更高。
修改后的代码示例
import undetected_chromedriver as uc from selenium.webdriver.common.by import By import requests import os from time import sleep chrome_options = uc.ChromeOptions() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") # 初始化浏览器并执行登录逻辑 driver = uc.Chrome(options=chrome_options) # --- 插入你的网站登录代码 --- # 打开目标图片页面 driver.get('https://www.your-target-website/image-url.jpg') sleep(3) # 获取图片URL和登录态Cookie image_element = driver.find_element(By.XPATH, '/html/body/img') image_url = image_element.get_attribute('src') cookies = {cookie['name']: cookie['value'] for cookie in driver.get_cookies()} # 指定保存目录并确保目录存在 save_dir = r"C:/Users/ExampleUser/Documents/ExampleFolder/" os.makedirs(save_dir, exist_ok=True) image_filename = image_url.split('/')[-1] save_path = os.path.join(save_dir, image_filename) # 下载并保存图片 response = requests.get(image_url, cookies=cookies, stream=True) response.raise_for_status() with open(save_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) driver.quit()
解决方案二:调整Chrome下载偏好设置
若坚持使用浏览器原生下载,可补充更多配置参数规避安全拦截:
修改后的偏好设置
prefs = { "download.default_directory": r"C:/Users/ExampleUser/Documents/ExampleFolder/", "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": False, "profile.default_content_setting_values.automatic_downloads": 1, "download.extensions_to_open": "", "profile.content_settings.exceptions.automatic_downloads.*.setting": 1 } chrome_options.add_experimental_option("prefs", prefs)
额外注意:
- 使用原始字符串(
r"路径")或双反斜杠避免路径转义错误 - 确保目标目录有写入权限(避开系统保护目录)
- 关闭浏览器安全浏览相关功能
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

