Skip to main content
 首页 » 编程设计

python之使用 python selenium 下载

2024年11月24日17kevingrace

我想从网站下载文件。在该网站中,我单击一个按钮打开一个小子窗口,该窗口有一个按钮,单击该按钮可将文件下载到目录 path_here。这是我的解决方案:

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options 
 
chrome_options = Options() 
 
chrome_options.add_argument('--dns-prefetch-disable') 
chrome_options.add_experimental_option("prefs", { 
  "download.default_directory": r'path_here', 
  "download.prompt_for_download": False, 
  "download.directory_upgrade": True, 
  "safebrowsing.enabled": True 
}) 
driver = webdriver.Chrome("./chromedriver", options=chrome_options) 
 
website = "https://www.chess.com/ccc" 
driver.get(website)  # loads the page 
# This closes a sub-window that opens automatically 
element = driver.find_element_by_class_name("form-button-component") 
element.click() 
 
driver.find_element_by_class_name("icon-download").click() 
download = driver.find_element_by_class_name('download-pgn') 
# Click to download 
download.find_element_by_class_name("btn").click() 

这应该可以,但没有像我预期的那样下载文件。为了完整起见,我添加了一个屏幕截图:

按钮为下载游戏(PGN),其文本通过print(download.find_element_by_class_name("btn").text)获取

请您参考如下方法:

In the website I click on a button that opens a small sub-window

在这里您提到您正在打开一个新的子窗口,您必须在其中单击按钮进行下载。但是你没有切换到那个窗口。因此无法找到该元素。

使用 driver.window_handles 获取打开窗口的句柄并使用 driver.switch_to_window() 切换到该窗口,然后尝试点击按钮进行下载。

您可以在此 stackoverflow 中了解如何在 python selenium 中处理多个窗口 link .

编辑:

看来您的代码中存在一些问题。就像棋盘旁边的下载按钮定位器和后面那个定位器是不正确的。我已经使用正确的 xpath 更正了定位器,并且对 chrome_options 也做了一些小改动。您只需将 download.defualt_directory 更改为您机器中的路径,下面的代码就可以运行:

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options 
 
chrome_options = Options() 
 
chrome_options.add_experimental_option("prefs", { 
  "download.default_directory": r"C:\Users\Thanthu Nair\Downloads\Test", 
  "download.prompt_for_download": False, 
  "download.directory_upgrade": True, 
  "safebrowsing.enabled": True 
}) 
driver = webdriver.Chrome("./chromedriver", options=chrome_options) 
 
website = "https://www.chess.com/ccc" 
driver.get(website)  # loads the page 
driver.maximize_window() 
 
# This closes a sub-window that opens automatically 
element = driver.find_element_by_class_name("form-button-component") 
element.click() 
 
download = driver.find_element_by_xpath("//i[@title='Download']") 
download.click() 
 
# Click to download 
download.find_element_by_xpath("//button[normalize-space()='Download Game (PGN)']").click()