Fail To Download File With Opened New Tab In Headless Mode On Linux
As this answer by myself: How to download files headless in Selenium (Java) when download happens in new tab? If download button trigger download action in opened new tab, I will
Solution 1:
if there is a new tab is opened when you click on a download link (for example if it has target="_blank"
attribute ). In such case download in headless with the enable_download_in_headless_chrome method, a solution doesn't work. So you can remove target="_blank"
attribute by JS or get href and try to download by direct opening the link in the same tab.
if there is link and open in new tab then you can open in the same tab by overwriting javascript
defopen_link_same_tab_download_file(current_user_driver, element):
# open element in same tab add target to self
current_user_driver.execute_script('arguments[0].target="_self"',element)
# click on element to download file
current_user_driver.execute_script("arguments[0].click()", element
if there is no link attribute then you can override javascript of open window in new tab like below
defopen_new_tab_download_file(current_user_driver, element):
# open element in same tab override javascript for that
current_user_driver.execute_script('window.open = function(url) {window.location=url}')
# click on element to download file
current_user_driver.execute_script("arguments[0].click()", element)
Solution 2:
On Linux, I found that the file will be downloaded two times through below code:
# Open new tab by clicking download button
download_button.click()
# Switch to new tab
driver.switch_to.window(driver.window_handles[-1])
# Wait for ready state
WebDriverWait(driver, 60).until(lambdadriver: driver.execute_script('return document.readyState') == 'complete')
##### The file will be downloaded to original download path ##### # Change download directory
enable_download_in_headless_chrome(driver, download_path)
# Refresh to trigger download behavior again
driver.refresh()
##### The file will be downloaded to your specific path again #####
If send "enable download" command before ready state, it cannot change download directory successfully.
Post a Comment for "Fail To Download File With Opened New Tab In Headless Mode On Linux"