我想从网站下载文件。在网站上,我单击一个按钮,该按钮会打开一个小子窗口,该窗口具有一个按钮,单击该按钮会将文件下载到目录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)
答案 0 :(得分:1)
在网站上,我单击一个按钮,打开一个小子窗口
这里您提到要打开一个新的子窗口,在该窗口中单击按钮进行下载。但是您不会切换到该窗口。因此无法找到该元素。
使用driver.window_handles
获取打开的窗口的句柄,然后使用driver.switch_to_window()
切换到该窗口,然后尝试单击按钮进行下载。
您可以在此stackoverflow link中看到如何在python硒中处理多个窗口。
编辑:
因此,似乎您的代码中存在一些问题。就像国际象棋棋盘旁边的下载按钮定位器一样,之后的那个不正确。我已经用正确的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()