Download a pdf from Chrome Viewer using selenium python - python

I am trying to log into an application, navigate to a pdf link, click on it. The pdf opens in chrome viewer. Download the pdf file. Download part is getting error: "DeprecationWarning: use options instead of chrome_options WebDriver = webdriver.Chrome(chrome_options=options)" and the pdf does not get downloaded
I've looked at all the solutions online and am doing something wrong. New to this.
Please correct me. Any help is much appreciated!
from time import sleep
import self as self
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver import Chrome, ChromeOptions
*# mulitple drivers for other aspects of the code. Not relevant to the question so excluded.*
WebDriver = webdriver.Chrome(service=ChromeService(executable_path=ChromeDriverManager().install()))
driver = WebDriver.get("open application") *(links changed)*
*#click on pdf file*
wait = WebDriverWait(WebDriver, 10)
WebDriver.find_element(By.ID, "XXXX").click() **(ID excluded as its restricted to post)**
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {
"download.default_directory": "C:/Downloads/POD",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True
}
)
WebDriver = webdriver.Chrome(chrome_options=options)

There are several issues here.
You've defined multiple Chromedriver instances. You should only need one.
WebDriver.get() doesn't return anything but you've assigned it to driver.
You've defined your ChromeOptions() after you've already created one driver instance.
DeprecationWarning is not an error, it's a warning. It's basically telling you that you're using code in a way that's not going to be supported in the near future.
Your code should look something like
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {
"download.default_directory": "C:/Downloads/POD",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True
}
)
WebDriver = webdriver.Chrome(service=ChromeService(executable_path=ChromeDriverManager().install()), options=options)
WebDriver.get("http://www.sample.com")
#click on pdf file
WebDriver.find_element(By.ID, "someId").click()

Related

python selenium sendkey doesn't work in chrome

I'm trying to launch some browser (Chrome) functions by sending shortcuts
I have tried several methods but they all cannot work.
I do this by following these steps
Initialize the browser
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
options = Options()
options.add_argument("--user-data-dir="+r"path_to_user_data")
options.add_experimental_option("excludeSwitches", ["enable-logging"])
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())
,options=options
)
Through actionchain
ActionChains(driver).key_down(Keys.CONTROL).key_down('T').key_up('T').key_up(Keys.CONTROL).perform
Through send_key
driver.find_element(by=By.XPATH,value="/html/body").send_keys(Keys.CONTROL+"T")
But it doesn't work. This is confused for me. Why it cannot work?
It is possible to open a new tab and switch to it with a single command
driver.switch_to.new_window()
To Open a blank new tab you can use the below:
driver.execute_script("window.open('');")
Switch to the new window
driver.switch_to.window(driver.window_handles[1])

Python selenium Open the link instead of download it

I have an automation project that requires opening the URL to a Microsoft SharePoint file and performing some action on the website instead of downloading it.
In my excel, if i "click" the hyperlink I can get directly opened up in the browser using the always open file option in chrome.
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
#url that generated from my Excel file containing hyperlink
df = pd.DataFrame(['https://company.sharepoint.com/sites/Test.xlsx', 'https://company.sharepoint.com/sites/Test2.xlsx'])
df.columns = ['url']
options = Options()
driver = webdriver.Chrome(options = options)
for url in df.url:
driver.get(url)
it just downloads the file instead of opening it in the browser if i code it using Selenium to open these url link
At least in Chrome you should be able to prevent the save file dialog from opening and to specify a download directory.
from selenium import webdriver
options = webdriver.ChromeOptions()
prefs = {
'download.default_directory': '/tmp',
'download. prompt_for_download': False,
}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=options)

Excel File is not downloaded using selenium we driver. Element is clicked but file isn't getting downloaded

I tried to download one excel file using the python selenium web-driver. After running the code I noticed that file is not downloaded (may be a source restriction). I am unable to figure out whether this can be handled or not. below is my code
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
ChromeDriver_Path = ChromeDriverManager().install()
options = Options()
options.binary_location = GoogleChrome_Path
options.add_argument("--headless")
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-extensions')
options.add_argument("--proxy-server='direct://'")
options.add_argument("--proxy-bypass-list=*")
options.add_argument('window-size=1920x1080')
Source_Export_Path = r'myfolderpath'
options.add_experimental_option("prefs", {"download.default_directory": Source_Export_Path,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
})
Source_Url = 'https://www.rbnz.govt.nz/statistics/j10-insurance-income-statement?__cf_chl_jschl_tk__=GXpMiuooASSLEEV4GrC0ODNHt3tzhq3PE2pXI_hoUsw-1641891789-0-gaNycGzNC6U'
driver = webdriver.Chrome(executable_path= ChromeDriver_Path, options = options)
driver.get(Source_Url)
element_1 = driver.find_element_by_css_selector(
'#RbnzContent > div.table.summaryinfo-table > div:nth-child(5) > div.summaryinfo-data.col-lg-8.col-md-9.col-sm-12.col-xs-12 > a:nth-child(2)'
).click()
but when I check my directory I see that there are no files downloaded. I even checked the selenium browser window and I noticed that website isn't letting python script to download the file using automated way. Is there any way to fix this issue!!.
This is the url:
try adding a delay / wait before clicking the element.
Expected conditions explicit wait is the preferred way to do that.
Also, you could improve the locator.
Also in case the code you shared is all your code you can add a delay after the clicking on the download button otherwise the session will close immediately after the click so file will be not downloaded.
Let me know if this worked better:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
ChromeDriver_Path = ChromeDriverManager().install()
options = Options()
options.binary_location = GoogleChrome_Path
options.add_argument("--headless")
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-extensions')
options.add_argument("--proxy-server='direct://'")
options.add_argument("--proxy-bypass-list=*")
options.add_argument('window-size=1920x1080')
Source_Export_Path = r'myfolderpath'
options.add_experimental_option("prefs", {"download.default_directory": Source_Export_Path,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
})
Source_Url = 'https://www.rbnz.govt.nz/statistics/j10-insurance-income-statement?__cf_chl_jschl_tk__=GXpMiuooASSLEEV4GrC0ODNHt3tzhq3PE2pXI_hoUsw-1641891789-0-gaNycGzNC6U'
driver = webdriver.Chrome(executable_path= ChromeDriver_Path, options = options)
wait = WebDriverWait(driver, 20)
driver.get(Source_Url)
wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contains(#href,'Statistics') and(contains(text(),'Insurance'))]"))).click()
time.sleep(10)

How can I download a file in the desired location with chrome using Python?

I tried the following code to change the default download location of chrome. But still, the file is downloaded at "Downloads".
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
ChromeOptions=Options()
ChromeOptions.add_experimental_option("prefs", {"download.default_directory":"C:\\Users\Elite\Desktop"})
driver=webdriver.Chrome(executable_path='C:\Webdrivers\chromedriver.exe',chrome_options=ChromeOptions)
driver.get("url/website")
driver.find_element_by_xpath('xpath of download file').click()
I also tried this:
options = webdriver.ChromeOptions()
options.add_argument('download.default_directory=C:/Users/Elite/Desktop')
driver=webdriver.Chrome(options=options)
Any help would be appreciated !!!!
Hi this is the Correct way to do it
Code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", {
"download.default_directory": r"C:\Users\Elite\Desktop",
"download.directory_upgrade":True,
"safebrowsing.enabled":True,
"download.prompt_for_download":False,
})
driver=webdriver.Chrome(executable_path="C:\Webdrivers\chromedriver.exe",options=options)
driver.get("url/website")
driver.find_element_by_xpath('xpath of download file').click()

"Failed - Download error" while download a file using Selenium Python

I was trying to download a file using selenium but getting "Failed - Download error".
I tried to disable the safe browsing but it didn't work.
I have attached the screenshot and code as well.
logs:
DevTools listening on ws://127.0.0.1:53738/devtools/browser/d75dfd5b-1e3e-45c5-8edd-adf77dd9adb1
[2572:2724:0717/104626.877:ERROR:device_event_log_impl.cc(208)] [10:46:26.877] Bluetooth: bluetooth_adapter_winrt.cc:1074 Getting Default Adapter failed.
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import csv
from selenium.webdriver.chrome.options import Options
link_list = [
"stewartwatson.co.uk",
"peterkins.com",
"gavin-bain.co.uk",
"martinco.com",
"tmmsolicitors.co.uk",
"corecitilets.co.uk",
"coxandco.co",
"dunechtestates.co.uk",
"bidwells.co.uk",
"kwad.co.uk",
]
options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", {
"download.default_directory": r"C:\\Users\\Awais\\projects\\selenium\\web_email_extractor\\csv",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": False,
"safebrowsing.ebabled": "false"
})
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.webemailextractor.com")
try:
driver.find_element_by_xpath('//button[contains(text(),"Close")]').click()
except:
pass
for i in link_list[0:5]:
text_area = driver.find_element_by_xpath('//textarea[#placeholder="Enter domain/websites list"]')
text_area.send_keys(i)
text_area.send_keys(Keys.ENTER)
submit = driver.find_element_by_xpath('//input[#value="Extract Email"]').click()
try:
btn = WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(), ' Process Completed')]")))
time.sleep(3)
csv_download = driver.find_element_by_xpath('//button[#class="dt-button buttons-csv buttons-html5"]').click()
except Exception as e:
print(e)
It worked when I removed the "r" from the path
"download.default_directory": r"C:\\Users\\Awais\\projects\\selenium\\web_email_extractor\\csv",
to:
"download.default_directory": "C:\\Users\\Awais\\projects\\selenium\\web_email_extractor\\csv",
Dear: When we configure the options of selenium is what will be defined in its configurations and as you write the route so considers it in the first photo you will see a well-configured route and a bad one, note bars there is the difference enter image description here
enter image description here

Categories