Open Chrome url in open tab with Python - python

I have to bring to front a Chrome tab (already open) with code.
More precisely, I have a tab (with its url) open in a Chrome browser (in kiosk mode) and, when the tab is in background, I want to bring it to front by means of a Chrome shortcut, an execuble file or a script.
The tab brought to front must be the same that was in background, and with the same url.
Can I do this with Python or by means of a Chrome shortcut, configuring its properties?

#Open google in python - Windows.
import webbrowser
url='https://google.com'
webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open(url)

Related

Where is the configuration to open a specific web browser in python?

This is a Win10 machine.
I have a file on disk called "test.html". When I run this in a terminal window C:\>test.html my default browser opens, and that is chrome.
Now I do the same in python
C:\> copy con test.py
import webbrowser
webbrowser.open('http://www.python.org')
^Z
1 file(s) copied.
C:\>python test.py
and Chrome, the default browser opens
But when I take an HTML response from an API call, and do the same webbrowser.open(...) then Internet Explorer opens. Not Edge, not Chrome, but Internet explorer.
How? It's almost as if there is something in the response that tells it "open with IE" except that if do it manually from the command line with C:\>response.html it opens chrome too.
Where is this instruction to open Internet Explorer coming from?
It should use your default browser. Otherwise, it falls back to IE
It appears to use os.startfile() to detect file associations, so running os.startfile('response.html') apparently throws a OSError for you, and you have no other browser installed in the list. Surprisingly, "chrome" nor "edge" is listed there.
Related - https://github.com/python/cpython/pull/11327
Another option you could try is to use something like webbrowser.open("file://c/response.html")
You can try webbrowser.get().
For example, opening a new tab in Google Chrome:
webbrowser.get(using='google-chrome').open_new_tab('https://google.com')
But it is not always possible to get by with .get () alone, and in this case the .register () function comes to the rescue, for example:
import webbrowser
webbrowser.register('Chrome', None, webbrowser.BackgroundBrowser('C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'))
webbrowser.get('Chrome').open_new_tab('google.com')
You can also check these links:
https://docs.python.org/3/library/webbrowser.html
http://pymotw.com/2/webbrowser/
https://discourse.world/h/2019/10/10/How-to-open-a-link-in-Python.Working-with-WebBrowser-and-solving-a-problem-with-Internet-Explorer

"This is the initial start page for the WebDriver server" - Unable to resolve in Selenium/Python program using IE 11

After running my Selenium/Python program, browser opened with below message:
This is the initial start page for the WebDriver server
I have done below steps to resolve this:
In IE Options -> Security tab, Enable Protected Mode check box is ticked OFF in all zones: Internet,
Local Intranet, Trusted sites and Restricted sites. Also, in Advanced tab -> Security, ticked OFF the
check box: "Enable Enhanced Protected Mode" (Also, I tried with enabling this Protected Mode in all
zones and in Advanced tab too).
My IEdriver (version 3.1.4) and Selenium web driver (version 3.1.4) are compatible (both are on same
version)
I tried above two, still I am getting the same message.
I have added below content to ignore Protected mode:
caps = DesiredCapabilities.INTERNETEXPLORER
caps['ignoreProtectedModeSettings'] = True
driver = webdriver.Ie(executable_path='C:/Selenium/Drivers/IEDriverServer.exe',capabilities=caps)
Still, I am getting the same message after adding above code.
Any ideas? Please help.
This is as per design. When IEDriverServer.exe opens a new a new Browsing Context i.e. Internet Explorer browsing session it navigates first to this page.
Browser Snapshot
Once you initialize the browser through the line:
driver = webdriver.Ie(executable_path='C:/Selenium/Drivers/IEDriverServer.exe',capabilities=caps)
next you can invoke the get() command to access any url. As an example:
driver.get('https://www.google.com/')
Additional Consideration
Additionally you need to:
Upgrade Selenium to current levels Version 3.141.59.
Upgrade IEDriverServer to latest IEDriverServer v3.150.1 level.
Note: As per best practices as Selenium Client and InternetExplorerDriver are released in sync and you must try to use both the binaries from the same major release.
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
Execute your #Test.
Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Open URL in Python in existing tab

I'm using webcommands to control a Sonoff. To change the setting I run the following line in Python:
webbrowser.open('http://Sonoff_IP/cm?cmnd=POWER%20TOGGLE')
I am looking for a way to run the URL in the same tab, so as not to create a new tab every time the command runs.
My understanding is that using if you are using webbrowser.open(<url>) it's not possible to avoid getting a new tab each time; with webbrowser it is possible to make sure it opens in the same browser window, but not in the same tab. To target the same window you need to set new=0 like:
webbrowser.open('http://Sonoff_IP/cm?cmnd=POWER%20TOGGLE', 0);
However, if you are able to open the link using the selenium library instead it is possible.
Read the docs for selenium and webdriver here: https://selenium-python.readthedocs.io/api.html
The main issue with doing it using Selenium is that, I think, you lose the ability to target the user's default web browser, and by default Selenium seems to default to Firefox since a lightweight port of Firefox is included in the Selenium library itself.
An example of opening a link in Selenium would be like:
from selenium import webdriver
link1="https://www.google.com"
link2="https://www.youtube.com/"
driver=webdriver.Firefox()
driver.get(link1)
driver.get(link2)
Selenium does support a lot of different browsers, so if you are able to get the user's default web browser from the webbrowser module or by some other method, you would be able to use that information to open URLs in the same tab with the user's default browser.
Hope this helps and good luck! :)
Use Javascript:
OpenSameTab = '<script language="JavaScript" type="text/JavaScript">window.location = \'%s\';</script>'
and then
print OpenSameTab % 'file.py'

Unable to interact with dialog box using selenium in Python

I am using "Python-3.4.1 32 bit" on "Windows 7 64 bit" machine with "Selenium" using "Firefox 33". I am trying to automate downloading a "CSV" file from a secured website after furnishing the necessary credentials.
I have written the required code to navigate to the correct element to initiate the download of the file but I am stuck when Firefox gives the download box (Dialog box title: Opening export.csv, "Open with" and "Save File" options as radio buttons with "OK" and "Cancel" as buttons). I want the file to be downloaded automatically and for that I have tried the following codes without success:
from selenium import webdriver
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.dir", "C:\\Users\\arun\\Downloads")
fp.set_preference("browser.download.downloadDir", "C:\\Users\\arun\\Downloads")
fp.set_preference("browser.download.defaultFolder", "C:\\Users\\arun\\Downloads")
fp.set_preference('browser.helperApps.neverAsk.saveToDisk',"text/csv")
fp.set_preference("browser.helperApps.neverAsk.openFile", "CONTENT-TYPE")
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","CONTENT-TYPE")
driver = webdriver.Firefox(fp)
driver.get("http://website-url.com")
and then click on the button to start the download. But, it still shows the dialog box. I even tried handling it as an alert and tried:
alert = driver.switch_to_alert()
alert.accept()
but this always gave an exception of alert not found which led me to the conclusion that it might not be a JavaScript functionality after all but rather a web element.
What do I do to get this downloaded automatically without the dialog box interaction (the way it's handled in Google Chrome browsers)
Thanks for your help and time
Cheers!
You set browser.helperApps.neverAsk.saveToDisk to text/csv and then two lines later you set it to CONTENT-TYPE.
According to this page this preference is interpreted as a list of MIME types. CONTENT-TYPE is not a valid MIME type and it has no other special meaning. You want to remove the 2nd assignment to browser.helperApps.neverAsk.saveToDisk. You probably also don't want the assignment to browser.helperApps.neverAsk.openFile.
Once, your browser.helperApps.neverAsk.saveToDisk is set properly, you should not have to worry about accepting a dialog box.
Selenium doesn't allow interaction with dialog windows (Save As dialog windows, for example). selenium is a web driver, so it only interacts with the browser.
I recommend using pywinauto and pywin32. It is a form of windows automation.
The problem is that selenium will "pause" while the dialog window is up, so to achieve this, the only way I know would be to write two scripts. The first would be the selenium / web automation process, and the other one the windows automation using pywinauto and/or pywin32.
You can then call the windows automation script at the end of the selenium/web automation script by:
import subprocess
subprocess.call("python C:\Python27\Scripts\windowsAutomation.py", shell=True)
One more thing, I am using FireFox 31
You can try with Chrome chrome browser if all else fails. Chrome will not ask for download location but you have to enable multiple file download and set a save location

Downloading file to specified location with Selenium and python

Ok so far i have my programing going to the website i want to download link from and selecting it, then the firefox dialogue box shows up and i don't know what to do. i want to save this file to a folder on my desktop. I am using this for a nightly build so i need this to work. Please help.
Here is my code that grabs the download link from the website:
driver = web driver.Firefox()
driver.implicitly_wait(5)
driver.get("Name of web site I'm grabbing from")
driver.find_element_by_xpath("//a[contains(text(), 'DEV.tgz')]".click()
You need to make Firefox save this particular file type automatically.
This can be achieved by setting browser.helperApps.neverAsk.saveToDisk preference:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", 'PATH TO DESKTOP')
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip")
driver = webdriver.Firefox(firefox_profile=profile)
driver.get("Name of web site I'm grabbing from")
driver.find_element_by_xpath("//a[contains(text(), 'DEV.tgz')]").click()
More explanation:
browser.download.folderList tells it not to use default Downloads directory
browser.download.manager.showWhenStarting turns of showing download progress
browser.download.dir sets the directory for downloads
browser.helperApps.neverAsk.saveToDisk tells Firefox to automatically download the files of the selected mime-types
You can view all these preferences at about:config in the browser. There is also a very detailed documentation page available here: About:config entries.
Besides, instead of using xpath approach, I would use find_element_by_partial_link_text():
driver.find_element_by_partial_link_text("DEV.tgz").click()
Also see:
Access to file download dialog in Firefox
Firefox + Selenium WebDriver and download a csv file automatically
If the application is generated dynamically (mime-types) using Chrome browser will be a better approach since the Chrome will not open the file download pop-up.But multiple download option should be enabled if you need multiple downloads.

Categories

Resources