Python: 3.9.9
Selenium: 4.1.5
Edge: 101.0.1210.39 (X64) driver link
I am trying to automate downloading excel file from a website, but due to Edge's default setting of open office files in browser set to True, on pressing download button with selenium it redirects to Edge file viewer instead of downloading it.
Since I want to automate the process I don't want to manually go to settings and disable it every time.
Any work arounds will be appreciated too...
Thank you!
This is what worked for me:
from pathlib import Path
from selenium import webdriver
if Path('..\msedgedriver.exe').exists():
driver = webdriver.Edge('..\msedgedriver.exe')
# Settings
driver.get('edge://settings/downloads')
toggle = driver.execute_script('''
return document.querySelector(' input[aria-label="Open Office files in
the browser"]');
''')
toggle.click()
# continue...
similarly you can change any setting as per required.
Related
Following info on this answer (How to load default profile in Chrome using Python Selenium Webdriver?) I have this piece of code which works fine provided Chrome is not open, otherwise an error is given.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chromeDriverPath = 'C:\\Users\\xxxx\\AppData\\Local\\SeleniumBasic\\chromedriver.exe'
userdatadir = 'C:\\Users\\xxxx\\AppData\\Local\\Google\\Chrome\\User Data'
chromeOptions = webdriver.ChromeOptions()
tmp = f"--user-data-dir={userdatadir}"
chromeOptions.add_argument(tmp) #Path to your chrome profile
driver = webdriver.Chrome(chromeDriverPath, options=chromeOptions)
print(driver.current_url)
If Chrome is already open this is the error: Message: invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir
A possible workaround is to (programmatically) copy the Chrome default directory into a new one. This way all settings and cookies are copied as well.
Problem, in my case, is that this directory is >2GB; I can't every time copy so much data... It has no sense.
So is it impossible or can anyone help in opening Chrome with default profile even if it is open?
The answer is you cannot open two session with 1 user-directory. Web-driver won't let you do this, It is like to rename a file in Windows when the file is open.
If you want to open chrome without user-dir, you can simply open with --incognito it will not store anything or use user-dir.
Otherwise you have to close the session with driver.quit() at the end of the test (teardown). So you can run the next test without problem.
Or you can use another user direcotry path, so the sessions will not interfers each other
I want to automatically download a .ics file (a calendar file) from a website using selenium with python. The goal is to disable the pop-up window that firefox open when you download a file. To do this, I use the following code :
#I set my preferences
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)#not using default folder for downloading
profile.set_preference("browser.download.manager.showWhenStarting", False)#dont show downloading process
profile.set_preference("browser.download.dir", 'C:/Users/UserName/Documents/rpi/some folder')#set the directory for download
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/calendar')#tell it to automaticaly download a file
#using the profile to access firefox
browser = webdriver.Firefox(executable_path='geckodriver',firefox_profile=profile)
I first thought that it was a MIME type problem in the line browser.helperApps.neverAsk.saveToDisk, but after changing the MIME type it's still not working.
From here I have no idea of what is going wrong because my MIME type seems right according to all internet resources I have been able to find.
Perhaps it is a problem of settings or something I haven't noticed...
Anyway thank you for reading this, ask me if you need a bit more code.
Hello from what I understand, downloading the file prompts a alert box asking if you want to download it, have you tried,
browser.switchtoalert.accept?
Sorry i write in VBA, but you should get the idea,
Thanks
So I did find a solution by avoiding the problem : i created a new firefox profile > launched firefox with this profile (all of this is done in about:profiles) > went to the web site from wich I wanted to download the file > downloaded the file and checked the "always do this with this type of file" box > launch my programm with this custom profile using the line :
profile= webdriver.FirefoxProfile("C:/Users/user/AppData/Roaming/Mozilla/Firefox/Profiles/bqpa3bzv.nameofprofile")
This seems to work fine and might be an efficient way of doing this.
Well done for figuring it out, I know the
.switchtoalert.accept works in chromedriver
Let me know if you want any help with anything 👍👍
I am trying to click on open application alert using Selenium, and I am getting this error
NoAlertPresentException: Message: no such alert
So basically I am trying to open zoom application from the browser
And here is my code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
driver = webdriver.Chrome(executable_path='chromedriver/chromedriver')
driver.get("https://zoom.us/j/93459172503?pwd=QkhnMEQ0ZTRZd0grUVJkT2NudmlFZz09")
try:
WebDriverWait(driver, 5).until(EC.alert_is_present(), 'Timed out waiting for alerts to appear')
alert = driver.switch_to.alert
alert.accept()
print("alert accepted")
except TimeoutException:
print("no alert")
Thanks to NetworkMeister, I end up using default app method, Like the following:
1- Open Firefox and go to zoom URL, when Launch application appear choose zoom and click on remember my choice and click open link
2- Go to firefox and paste this about:support then search for Profile Folder and copy the path
3- Go to your code and add profile parameter to selenium driver and use the path you have copied
fp = webdriver.FirefoxProfile('C:/Users/ASUS//AppData/Roaming/Mozilla/Firefox/Profiles/0rgewd47.default-release')
driver = webdriver.Firefox(executable_path='geckodriver', firefox_profile=fp)
driver.get('https://zoom.us/j/93459172503?pwd=QkhnMEQ0ZTRZd0grUVJkT2NudmlFZz09')
Now zoom application will open automatically when you execute this code
Note: Firefox profile contains all of your browsing data, If you want to share your code I suggest creating a new Firefox profile, For more information look here
Because this is not a browser Alert, rather OS App selector, you cannot interact with it within Selenium.
See: Selenium C# How to handle Alert "Open Pick an app"?
You can prevent these App selectors by default by using the --disable-default-apps flag when starting up Chrome.
I encountered this problem my self.
Apparently this is related to the alert being OS level rather than being at a browser level.
The simplest solution I found is https://pypi.org/project/PyAutoGUI/ which allows you to pass an img of the button you want to click and then it locates it on the screen. You can call python directly from java.
Native java solution: https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html
this allows you to automate stuff like "move mouse to position" -> "mouse click" etc.
EDIT: the main downside is that the webdriver cannot be run in headless mode as PyAutoGUI makes a screenshot of the screen to locate the button.
From what I noticed is that when you open any such link in the browser the URL changes a bit. With this you can figure out the link for opening it in the browser. For example I have this zoom meeting
https://us04web.zoom.us/ w/ 76919011107?tk=5Q_zikLZhvWlqc_nzVcYaHoTyo7JuDY6cvLB9y9t0zc.DQIAAAARDLr3IxZHM21mSHFzYlR6Q0xZdnNhcnUwbUV3AAAAAAAAAAAAAAAAAAAAAAAAAAAA&pwd=QANkcTdsNlpjYWY4czZvd3FHV0NLQT09
Now this would open a popup like you showed in the browser. (This link is not real. I changed 2-3 characters in the URL for security reasons). But now if you try this link
https://us04web.zoom.us/ wc/join/ 76919011107?tk=5Q_zikLZhvWlqc_nzVcYaHoTyo7JuDY6cvLB9y9t0zc.DQIAAAARDLr3IxZHM21mSHFzYlR6Q0xZdnNhcnUwbUV3AAAAAAAAAAAAAAAAAAAAAAAAAAAA&pwd=QANkcTdsNlpjYWY4czZvd3FHV0NLQT09
This will directly open the meeting in the browser. Note the change in URL has been shown in bold (I had to add spaces because of that on both sides). Now this may change over time but fundamentally by comparing the 2 links you should find a way to achieve this.
Similarly for Microsoft Teams if you add "_#" after the domain you can join the meeting through the browser
For example if I want to open this link in the browser
https://teams.microsoft.com/l/meetup-join/19%3ameeting_NTRlM2JiZWUtZjNiMC00ZjVhLTlmMWEtZDcxYjBmYjdhY2Nl%40thread.v2/0?context=%7b%22Tid%22%3a%22e85f2c00-2730-4ca5-b8d8-609b15bd4746%22%2c%22Oid%22%3a%223bf1c992-96b1-4a87-808f-dcc5bb2009c9%22%7d
I'll have to write
https://teams.microsoft.com/_#/l/meetup-join/19%3ameeting_NTRlM2JiZWUtZjNiMC00ZjVhLTlmMWEtZDcxYjBmYjdhY2Nl%40thread.v2/0?context=%7b%22Tid%22%3a%22e85f2c00-2730-4ca5-b8d8-609b15bd4746%22%2c%22Oid%22%3a%223bf1c992-96b1-4a87-808f-dcc5bb2009c9%22%7d
These patterns can be found by observing the link before and after opening it in the browser.
This is not the best way but I resolved the issue by sending keyboard commands. It works on Windows, I haven't tested on different os.
import pyautogui
sleep(3) # sleep until pop up shown
pyautogui.press('tab', presses=2) # navigate to open button
pyautogui.press('enter') # open application
For me using Robot class worked for teams.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
I am trying to use Selenium in Python to download a file from a website. In order to do that, I have read that I need to change the settings in my Firefox Profile to avoid opening the download dialogue window. I provided sample code below. This code works absolutely great at home, but it does not function properly with my work PC. I am suspecting that somehow Python can not change the settings of the firefox profile, even though the code below does not throw an error but rather works fine and in the end opens the download dialogue window.
from selenium import webdriver
import os
profile = webdriver.FirefoxProfile("C:\\Users\\Ric\\Documents\\Python Scripts\\FirefoxProfileCopies\\ric.copy")
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',('application/vnd.ms-excel'))
browser = webdriver.Firefox(profile)
browser.get("http://www.sample-videos.com/download-sample-xls.php")
elem1 = browser.find_element_by_css_selector(".push-form > table:nth-child(2) > tbody:nth-child(2) > tr:nth-child(4) > td:nth-child(4) > a:nth-child(1)")
elem1.click()
This code works perfectly with my Firefox and its profile at home, but not with my computer at work. Does anybody know why this might be? Thank you in advance.
EDIT
I tried to add all the MIMEtypes from the Microsoft webpage, but still, the download manager window opens. When stopping the code to execute before opening the download link and trying to look at the settings for the used firefox profile with about:configthe following values are displayed:
So, after a lot of trying, I figured to look at the firefox settings in Firefox again, since it worked with an empty profile. I managed to resolve my issue and finally have the download window disappear by going to firefox, settings and changing the settings for applications:
Then, when opening this menu, search for excel and change the values from "asking every time" to "save file/download file". Sorry if these entries in the list differ from the actual ones in firefox but my Firefox is in German. After doing this, my issue was resolved. I hope it resolves somebody else :) and thanks to anderson.
i am using this addon with selenium and it starts fine, but how do you go about affecting the settings of addons in selenium?
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox import webdriver
profile = FirefoxProfile('/path/to/profile')
driver = webdriver.WebDriver(firefox_profile = profile)
driver.get("http://localhost/referer.html")
driver.find_element_by_link_text("go there").click()
the problem is that this addon does not do anything unless you configure it first, but there is no documentation, that i can find on this.
General way, as alecxe suggested, "to install and configure the extension first, then use that firefox profile with selenium". This will probably work with any extension.
I also search for configuration in prefs.js (or about:conf) and found out, that it stores the value in "refcontrol.actions" preference. This way you will be able to change the extension behavior in your code. Example:
profile = FirefoxProfile('/path/to/profile')
profile.set_preference("refcontrol.actions", '#DEFAULT=#NORMAL example.com=#3RDPARTY:http://www.referer.com/your/referer');