webbrowser, opening chrome and internet explore for different url - python

url = 'http://www.google.org/'
chrome_path = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'
webbrowser.get(chrome_path)
webbrowser.open(url)
above will open chrome, which is what I want.
However if I change the url to url = 'reddit it will open internet explore instead. Why does it open different webbrowsers for different urls? And how can I make sure it opens in chrome for all urls?

Do this:
>>> import webbrowser
>>> browser = webbrowser.get()
>>> browser.open('http://google.com')
True
>>> browser.open_new_tab('http://yahoo.com')
True
>>>
The webbrowser.get() call will get you a browser controller object. You can run open, open_new and open_new_tab on the controller object. This will ensure the commands are executed on the same browser instance you opened.
If you directly use webbrowser.open() - it will always open the link in the default browser, which in your case is Internet Explorer.
So to rewrite your code:
chrome_path = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
chrome = webbrowser.get(chrome_path)
chrome.open('http://google.com')
chrome.open_new_tab('http://reddit.com')

Related

im using the web browser import and i want to figure out if i can run a google link in incognito from webbrowser. is that possible?

I'm writing out a code that opens up all necessary tabs using the webbrowser module so that I don't have to open them all manually when I open my pc, but one of the links I want it to open in incognito mode (all the links are google links) is this possible? I don't want all the code to open on incognito mode I just want the Microsoft Teams URL to open in incognito. Thanks in advance.
my code:
import webbrowser
import time
webbrowser.open('https://www.youtube.com/')
time.sleep(0.3)
webbrowser.open('https://mail.google.com/')
time.sleep(0.3)
webbrowser.open('https://teams.microsoft.com')
The solution is to specify the browser executable with the appropriate command line arguments to start it in incognito mode. The exact flag may vary by browser. Firefox, for example, takes the -private-window flag to start in incognito mode.
import webbrowser
import time
firefox_path = 'C:/Program Files/Mozilla Firefox/firefox.exe'
incognito_browser = webbrowser.get(firefox_path + ' -private-window %s')
webbrowser.open('https://www.youtube.com/')
time.sleep(0.3)
webbrowser.open('https://mail.google.com/')
time.sleep(0.3)
incognito_browser.open('https://teams.microsoft.com')
# ...could use now incognito_browser to open additional sites as desired.
The '%s' is substituted with the URL during the call to open and must be present for get to recognize that a command line invocation is being supplied rather than a named browser instance, e.g. 'opera'.

Web browser chrome, can't open URL in new window, keeps opening URL as a tab

I'm trying to open a URL in a new window. I can't use selenium because it wouldn't be signed into Google.
My default browser is Chrome using Windows 10 and I already have 3 Chrome windows open each with multiple tabs.
here is my code on Python 3.6:
import webbrowser
url = 'https://google.com'
open_google = webbrowser.open('https://google.com', new=1)
open_google = webbrowser.open_new('https://google.com')
Both of these give me a new tab in my current window instead of a new window. Why is this happening? is it a setting in Chrome?
How about opening a new window using os.system or subprocess and then using webbrowser to get the urls/apps to open there.
Something like:
import subprocess
command = "cmd /c start chrome http://www.google.com --new-window"
subprocess.Popen(command, shell=True)
and then doing:
open_google = webbrowser.open('https://google.com', new=1)
I want to be able to launch different browsers, because they have a different default theme and their displays look different on my computer.
Here is an approach that parameterizes the URL string to dynamically create the URL with the browser name "on the fly".
import subprocess
browser_type = "chrome" # Replace the value with "edge" or "firefox"
location_url = "https://stackoverflow.com/questions/7521729/how-to-open-a-new-default-browser-window-in-python-when-the-default-is-{browser_type}"
command_fstring = f"cmd /c start firefox {location_url} --new-window"
subprocess.Popen(command_string, shell=True)
To give credit where it is due, this is based on the answer by #Sharath on this page: Web browser chrome, can't open URL in new window, keeps opening URL as a tab

opening URL in browser with python (not headless)

I am not taking about headless browser.
I am writing an script, when a directory get a new file, it will open an url, when the file deleted from directory, it will open another url.
My Script is below:
import os, time
def folderListener(mydir):
old_list = len(os.listdir(mydir))
new_list = 0
while True:
new_list = len(os.listdir(mydir))
if old_list != new_list:
old_list = new_list
print('OPen first url in chrom browser')
else:
print('Open 2nd URL in Chrome Browser')
time.sleep(2)
if __name__ == '__main__':
mydir = os.getcwd() + '/testdir'
folderListener(mydir)
The script working very nice, now i need to it in the script when print function place. i mean, it should open an URL on Chrome Browser instead, no headless chrome browser.
You could look into webbrowser.
Used like:
import webbrowser
url = "http://mywebsite.com"
webbrowser.open_new(url) # open in default browser
webbrowser.get('safari').open_new(url) # open in safari if available
webbrowser.get('firefox').open_new_tab(url) # open in firefox if available
webbrowser.get(using='google-chrome').open_new(url) # open in chrome if available
But considering you tagged selenium-webdriver you could also do this:
from selenium import webdriver
url = "http://mywebsite.com"
driver = webdriver.Chrome()
driver.get(url)

Open url in existing browser not in default browser

I used below code to open new url
webbrowser.open(url)
This opened the url in the default browser, but I need to open it in a browser session that is already open.
Also, is there a way to open a URL in a specific tab of a browser?
You should use webbroser.get([name]): Return a controller object for the browser type name. If name is empty, return a controller for a default browser appropriate to the caller’s environment.
Demo:
import webbrowser
url = 'http://www.google.com'
browser = webbrowser.get('firefox') # or lynx, opera
browser.open(url)

How can I download a file on a click event using selenium?

I am working on python and selenium. I want to download file from clicking event using selenium. I wrote following code.
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get("http://www.drugcite.com/?q=ACTIMMUNE")
browser.close()
I want to download both files from links with name "Export Data" from given url. How can I achieve it as it works with click event only?
Find the link using find_element(s)_by_*, then call click method.
from selenium import webdriver
# To prevent download dialog
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/tmp')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')
browser = webdriver.Firefox(profile)
browser.get("http://www.drugcite.com/?q=ACTIMMUNE")
browser.find_element_by_id('exportpt').click()
browser.find_element_by_id('exporthlgt').click()
Added profile manipulation code to prevent download dialog.
I'll admit this solution is a little more "hacky" than the Firefox Profile saveToDisk alternative, but it works across both Chrome and Firefox, and doesn't rely on a browser-specific feature which could change at any time. And if nothing else, maybe this will give someone a little different perspective on how to solve future challenges.
Prerequisites: Ensure you have selenium and pyvirtualdisplay installed...
Python 2: sudo pip install selenium pyvirtualdisplay
Python 3: sudo pip3 install selenium pyvirtualdisplay
The Magic
import pyvirtualdisplay
import selenium
import selenium.webdriver
import time
import base64
import json
root_url = 'https://www.google.com'
download_url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'
print('Opening virtual display')
display = pyvirtualdisplay.Display(visible=0, size=(1280, 1024,))
display.start()
print('\tDone')
print('Opening web browser')
driver = selenium.webdriver.Firefox()
#driver = selenium.webdriver.Chrome() # Alternately, give Chrome a try
print('\tDone')
print('Retrieving initial web page')
driver.get(root_url)
print('\tDone')
print('Injecting retrieval code into web page')
driver.execute_script("""
window.file_contents = null;
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
window.file_contents = reader.result;
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', %(download_url)s);
xhr.send();
""".replace('\r\n', ' ').replace('\r', ' ').replace('\n', ' ') % {
'download_url': json.dumps(download_url),
})
print('Looping until file is retrieved')
downloaded_file = None
while downloaded_file is None:
# Returns the file retrieved base64 encoded (perfect for downloading binary)
downloaded_file = driver.execute_script('return (window.file_contents !== null ? window.file_contents.split(\',\')[1] : null);')
print(downloaded_file)
if not downloaded_file:
print('\tNot downloaded, waiting...')
time.sleep(0.5)
print('\tDone')
print('Writing file to disk')
fp = open('google-logo.png', 'wb')
fp.write(base64.b64decode(downloaded_file))
fp.close()
print('\tDone')
driver.close() # close web browser, or it'll persist after python exits.
display.popen.kill() # close virtual display, or it'll persist after python exits.
Explaination
We first load a URL on the domain we're targeting a file download from. This allows us to perform an AJAX request on that domain, without running into cross site scripting issues.
Next, we're injecting some javascript into the DOM which fires off an AJAX request. Once the AJAX request returns a response, we take the response and load it into a FileReader object. From there we can extract the base64 encoded content of the file by calling readAsDataUrl(). We're then taking the base64 encoded content and appending it to window, a gobally accessible variable.
Finally, because the AJAX request is asynchronous, we enter a Python while loop waiting for the content to be appended to the window. Once it's appended, we decode the base64 content retrieved from the window and save it to a file.
This solution should work across all modern browsers supported by Selenium, and works whether text or binary, and across all mime types.
Alternate Approach
While I haven't tested this, Selenium does afford you the ability to wait until an element is present in the DOM. Rather than looping until a globally accessible variable is populated, you could create an element with a particular ID in the DOM and use the binding of that element as the trigger to retrieve the downloaded file.
In chrome what I do is downloading the files by clicking on the links, then I open chrome://downloads page and then retrieve the downloaded files list from shadow DOM like this:
docs = document
.querySelector('downloads-manager')
.shadowRoot.querySelector('#downloads-list')
.getElementsByTagName('downloads-item')
This solution is restrained to chrome, the data also contains information like file path and download date. (note this code is from JS, may not be the correct python syntax)
Here is the full working code. You can use web scraping to enter the username password and other field. For getting the field names appearing on the webpage, use inspect element. Element name(Username,Password or Click Button) can be entered through class or name.
from selenium import webdriver
# Using Chrome to access web
options = webdriver.ChromeOptions()
options.add_argument("download.default_directory=C:/Test") # Set the download Path
driver = webdriver.Chrome(options=options)
# Open the website
try:
driver.get('xxxx') # Your Website Address
password_box = driver.find_element_by_name('password')
password_box.send_keys('xxxx') #Password
download_button = driver.find_element_by_class_name('link_w_pass')
download_button.click()
driver.quit()
except:
driver.quit()
print("Faulty URL")

Categories