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

无法点击.gif文件生成报告,WebDriver自动下载报告遇阻求助

解决WebDriver无法点击.gif生成报告并自动下载的问题

Hey Kob, let's work through this issue together! I'll break down the likely problems with your current code and walk you through fixes step by step:

1. 窗口切换时机错误

Your code tries to access new_window1 and new_window2 right after launching the driver—but those windows don't exist yet! You need to wait until after clicking the "EXPORT" link for the new window to load, then switch to it properly instead of hardcoding indices.

Here's how to fix the window switching part:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 点击EXPORT链接
Export = driver.find_element_by_link_text("EXPORT")
Export.click()

# 等待新窗口出现(最多等10秒)
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))

# 获取所有窗口句柄,切换到新打开的窗口
all_windows = driver.window_handles
for window in all_windows:
    if window != main_window:
        driver.switch_to.window(window)
        break

2. .gif元素定位方式不对

A .gif is almost always an <img> tag, not a text link—so find_element_by_link_text() won't work here. You need to locate it using attributes like alt, src, or its parent element. For example:

  • If the .gif has an alt text like "Generate Report":
generate_gif = driver.find_element_by_xpath("//img[@alt='Generate Report']")
  • If you know part of its src URL ends with .gif:
generate_gif = driver.find_element_by_css_selector("img[src$='.gif']")

Once you've got the correct locator, click the element:

generate_gif.click()

3. 配置Chrome自动下载(避免弹窗)

To make sure the report downloads automatically without a browser popup, set up Chrome's download preferences before launching the driver:

from selenium.webdriver.chrome.options import Options

# 配置下载路径和自动下载设置
chrome_options = Options()
download_path = "C:/Users/Kob/Desktop/Python projects/Downloads" # 替换成你的目标路径
chrome_options.add_experimental_option("prefs", {
    "download.default_directory": download_path,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
})

# 用配置好的选项启动ChromeDriver
driver = webdriver.Chrome(
    executable_path="C:/Users/Kob/Desktop/Python projects/Chrome webdriver/Chromedriver.exe",
    options=chrome_options
)

4. 等待下载完成

After clicking the .gif, you'll want to wait for the file to finish downloading. Add this helper function to check your download folder:

import os
import time

def wait_for_download(download_path, filename_keyword, timeout=30):
    start_time = time.time()
    while time.time() - start_time < timeout:
        for file in os.listdir(download_path):
            # 检查文件是否包含关键词,且不是未完成的下载(.crdownload后缀)
            if filename_keyword in file and not file.endswith(".crdownload"):
                print(f"Success! Downloaded file: {file}")
                return True
        time.sleep(1)
    print("Download timed out.")
    return False

# 调用函数等待报告下载(替换关键词为你的报告文件名特征)
wait_for_download(download_path, "export_report")

Full Modified Code

Putting it all together, here's your complete working script:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import os
import time

# 配置Chrome下载设置
download_path = "C:/Users/Kob/Desktop/Python projects/Downloads"
chrome_options = Options()
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(
    executable_path="C:/Users/Kob/Desktop/Python projects/Chrome webdriver/Chromedriver.exe",
    options=chrome_options
)
driver.get("http://www2.ops3.moc.go.th/")
main_window = driver.current_window_handle

# 点击EXPORT并切换到新窗口
Export = driver.find_element_by_link_text("EXPORT")
Export.click()
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
all_windows = driver.window_handles
for window in all_windows:
    if window != main_window:
        driver.switch_to.window(window)
        break

# 定位并点击生成报告的.gif(替换成你实际的元素定位器)
generate_gif = driver.find_element_by_xpath("//img[@alt='Generate Report']")
generate_gif.click()

# 等待下载完成
def wait_for_download(download_path, filename_keyword, timeout=30):
    start_time = time.time()
    while time.time() - start_time < timeout:
        for file in os.listdir(download_path):
            if filename_keyword in file and not file.endswith(".crdownload"):
                print(f"Success! Downloaded file: {file}")
                return True
        time.sleep(1)
    print("Download timed out.")
    return False

wait_for_download(download_path, "export_report")

# 关闭浏览器
driver.quit()

Quick Notes:

  • Replace the XPath/CSS selector for the .gif with the actual attributes from the page (use Chrome DevTools to inspect the element and get the correct locator).
  • Adjust the filename_keyword in the wait_for_download function to match your report's filename.
  • Make sure your ChromeDriver version matches your installed Chrome browser version to avoid compatibility issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:41:33