Open IE Browser Window - python

The webbrowser library provides a convenient way to launch a URL with a browser window through the webbrowser.open() method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on windows.
WindowsDefault only works if Internet Explorer is set as the default browser, which is not an assumption I can make.
Is there a way to explicitly launch a URL into Internet Explorer without reverting to windows API calls?

More elegant code:
import webbrowser
ie = webbrowser.get(webbrowser.iexplore)
ie.open('google.com')

>>> ie = webbrowser.get('c:\\program files\\internet explorer\\iexplore.exe')
>>> ie.open('http://google.com')
True

iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"Internet Explorer\\IEXPLORE.EXE")
ie = webbrowser.BackgroundBrowser(iexplore)
ie.open(...)
This is what the webrowser module uses internally.

You can always do something like
subprocess.Popen('"C:\\Program Files\\Internet Explorer\\iexplore.exe" http://www.example.com')

The simplest way:
import subprocess
subprocess.Popen(r'"C:\Program Files\Internet Explorer\IEXPLORE.EXE" www.google.com')

If you plan to use the script in more than your machine, keep in mind that not everyone has a English version of Windows
import subprocess
import os
subprocess.Popen(r'"' + os.environ["PROGRAMFILES"] + '\Internet Explorer\IEXPLORE.EXE" www.google.com')

Please try putting the absolute path of internet explorer exe file in your code.
ie=webbrowser.get("C:\Program Files\Internet Explorer\iexplore.exe")
ie.open_new("http://google.com")

Related

How can I open a website in my web browser using Python?

I want to open a website in my local computer's web browser (Chrome or Internet Explorer) using Python.
open("http://google.co.kr") # something like this
Is there a module that can do this for me?
The webbrowser module looks promising: https://www.youtube.com/watch?v=jU3P7qz3ZrM
import webbrowser
webbrowser.open('http://google.co.kr', new=2)
From the doc.
The webbrowser module provides a high-level interface to allow
displaying Web-based documents to users. Under most circumstances,
simply calling the open() function from this module will do the right
thing.
You have to import the module and use open() function. This will open https://nabinkhadka.com.np in the browser.
To open in new tab:
import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)
Also from the doc.
If new is 0, the url is opened in the same browser window if possible.
If new is 1, a new browser window is opened if possible. If new is 2,
a new browser page (“tab”) is opened if possible
So according to the value of new, you can either open page in same browser window or in new tab etc.
Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.
As the instructions state, using the open() function does work, and opens the default web browser - usually I would say: "why wouldn't I want to use Firefox?!" (my default and favorite browser)
import webbrowser as wb
wb.open_new_tab('http://www.google.com')
The above should work for the computer's default browser. However, what if you want to to open in Google Chrome?
The proper way to do this is:
import webbrowser as wb
wb.get('chrome %s').open_new_tab('http://www.google.com')
To be honest, I'm not really sure that I know the difference between 'chrome' and 'google-chrome', but apparently there is some since they've made the two different type names in the webbrowser documentation.
However, doing this didn't work right off the bat for me. Every time, I would get the error:
Traceback (most recent call last):
File "C:\Python34\programs\a_temp_testing.py", line 3, in <module>
wb.get('google-chrome')
File "C:\Python34\lib\webbrowser.py", line 51, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser
To solve this, I had to add the folder for chrome.exe to System PATH. My chrome.exe executable file is found at:
C:\Program Files (x86)\Google\Chrome\Application
You should check whether it is here or not for yourself.
To add this to your Environment Variables System PATH, right click on your Windows icon and go to System. System Control Panel applet (Start - Settings - Control Panel - System). Change advanced settings, or the advanced tab, and select the button there called Environment Varaibles.
Once you click on Environment Variables here, another window will pop up. Scroll through the items, select PATH, and click edit.
Once you're in here, click New to add the folder path to your chrome.exe file. Like I said above, mine was found at:
C:\Program Files (x86)\Google\Chrome\Application
Click save and exit out of there. Then make sure you reboot your computer.
Hope this helps!
Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
I think it should be
import webbrowser
webbrowser.open('http://gatedin.com')
NOTE: make sure that you give http or https
if you give "www." instead of "http:" instead of opening a broser the interprete displays boolean OutPut TRUE.
here you are importing webbrowser library
I had this problem.When I define firefox path my problem had been solved.
import webbrowser
urL='https://www.python.org'
mozilla_path="C:\\Program Files\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path))
webbrowser.get('firefox').open_new_tab(urL)
You can simply simply achieve it with any python module that gives you an interaction with command line(cmd) like subprocess, os, etc.
but here I came up with examples on only two modules.
Here is syntax (command) cmd /c start browser_name "URL"
Example
import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')
# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')
You can also run the command in the cmd it will work to or use other module call
click which mainly used for writing command line utilities.
here is how
import click
click.launch('http://your_url')
Its a 2 liner! :D
You are a great programmer so never give up!
#Use web-browser.
import webbrowser as w
w.open("https://google.com")
#remember to include https://
#If you want to make a page open if you click a button do this :
from tkinter import *
#^ Imports tk
import webbrowser as w
#^ Imports wb
x = Tk()
#Makes main window
def clicked() :
w.open("https://google.com")
#Defined the click function. (We'll use this later.)
link = Button(x, text="Click Me!", command=clicked)
link.pack(pady=20, padx=20)
#Our button
x.mainloop()
#Tkinter mainloop
If you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:
from threading import Timer
from time import sleep
import subprocess
import platform
# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser
# Hint 2: fullscreen will only work if chrome is not already running
platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}
browser = None
def open_browser():
global browser
platform_name = platform.system()
if platform_name in platform_browser:
browser = subprocess.Popen(platform_browser[platform_name])
else:
print(":-(")
Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch
sleep(20) # start e.g. your python web server here instead
browser.kill()
If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website.
e.g.
import webbrowser
webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)

How to open a newtab page using the webbrowser module in python?

I'm currently trying to open my chrome default new tab page using the webbrowser module in python. I've gotten it to work for opening up random urls, however, when I try chrome://newtab as the url, I just get a message saying that there are "no apps installed to open this type of link".
Here's the relevant bit of code (not much):
import webbrowser
webbrowser.open_new_tab("chrome://newtab")
Yes, chrome is my default browser. Thanks for the help!
Notice that the documentation states that:
Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.
It has been a while since I looked at this, but my recollection is that on at least some systems, the way it works under the hood is that is passes the given URI to a system specific built-in command which then opens the URI in the system default for whatever type of URI was passed in. In other words, the default application for a given file type is used. It doesn't matter if the URI points to a local file or not. Therefore, the URI http://examplce.comn/somefile.pdf would open the PDF file on the system default PDF viewer, which may not be the browser. As the documentation notes, this works by accident due to the underlying implementation.
However, in a different OS, such a system specific command doesn't exist, and all URIs will be opened in a web browser.
You failed to mention which OS you are working on (and I forget which OS works which way), but I suspect you are working on an OS of the first type. You might (again depends on which system you have) be able override the default behavior by specifying that a specific browser be used.
You could try setting the environment variable BROWSER as an os.pathsep-separated list of browsers to try in order. Check the value of os.pathsep (import os; print os.pathsep) to see which character is used by your system (usually ':' for POSIX or ';' for Windows) and then use that character to separate items in the list. Of course, you may need to only assign one item to the list (chrome), in which case you don't need to use the separator at all. Like this (be sure to use the correct path for your system):
SET BROWSER="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Or, you could try using webrowser.get() to choose your browser programically. However, support for Chrome hasn't been added until Python 3.3. If you are using Python 3.3+, then try:
import webbrowser
chrome = webbrowser.get('google-chrome') # or webbrowser.get('chrome')
chrome.open_new_tab('chrome://newtab')
Note: the above is untested. I don't know which system you have and am therefore not able to replicate your specific setup. YMMV.
Update:
As I now know you are on a pre-Python 3.3 windows machine perhaps the following will help. You can also register a browser so that Python knows about it:
pth = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(pth))
chrome = webbrowser.get('chrome')
chrome.open_new_tab('chrome://newtab')
Seemingly Bulletproof Rock Solid Command Line From Python Option
In development, the methods above worked well for me. Then I moved my code to a production server. I found different flavors of Windows don't all play the same with python's webdriver module - I was very bummed!
I needed a bulletproof method to open auto generated html reports in a specific order.
The code below is a modification of what I did that worked very well.
import subprocess as SP
import time
def display_reports_in_chrome(param_1, param_2):
front = f'start chrome.exe {param_1}\\reports\\' # beginning of command string
reports_list = [
'report_1.html', 'report_2.html', 'report_3.html', 'report_4.html']
url_list = []
for report in reports_list:
url_list.append(f'{front}{param_2}\\{report}') # complete build of commands
for url_cs in url_list: # url_cs = url open command string
time.sleep(0.1) # helps to ensure the tabs order correctly
clo = SP.run(url_cs, shell=True, capture_output=True) # actual shell command
# Stuff below makes sure it worked
check = clo.returncode == 0
error = clo.stderr.decode('utf-8')
url_open_ok = check and not error
err_msg = f'{error}. Let Thom know please!'
assert url_open_ok, err_msg
I should point out that I was enlightened to try this by this answer on SuperUser

How to open Google Chrome using Python and pass in arguments?

Here is how I am trying to do it:
# Start Google Chrome
subprocess.call(["C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "--kiosk"])
If I add the --kiosk flag to the Google Chrome shortcut on my desktop, Chrome does start in kiosk mode. However, when I try this through Python, it doesn't seem to work. I've searched Google and here, but have found nothing so far. Please help.
That command works for me just fine.
Make sure you're not running another copy of Chrome. It appears that Chrome will only start in Kiosk mode if no other instances are running. If you want to make sure no other instances are running, this answer shows how you could kill them before starting a new process:
import os
import subprocess
CHROME = os.path.join('C:\\', 'Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe')
os.system('taskkill /im chrome.exe')
subprocess.call([CHROME, '--kiosk'])
As a side note, it is always nice to use os.path.join, even if your code is platform-specific at this point.
You could use raw-string literals for Windows paths:
import subprocess
chrome = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
subprocess.check_call([chrome, '--kiosk'])
Note: "\\n" == r'\n' != '\n'. Though it doesn't make any difference in your case.
You could try to pass --new-window option to open a new window.
If all you need is to open an url in a new Google Chrome window:
import webbrowser
webbrowser.get('google-chrome').open_new('https://example.com')
Thanks for 'kill other instances' tip, solved my problem :)
I use the following method :
import os
os.system('taskkill /im chrome.exe')
os.system('start chrome "https://www.youtube.com/feed/music" --kiosk')

How to get a name of default browser using python

My script runs a command every X seconds.
If a command is like "start www" -> opens a website in a default browser I want to be able to close the browser before next time the command gets executed.
This short part of a script below:
if "start www" in command:
time.sleep(interval - 1)
os.system("Taskkill /IM chrome.exe /F")
I want to be able to support firefox, ie, chrome and opera, and only close the browser that opened by URL.
For that I need to know which process to kill.
How can I use python to identify my os`s default browser in windows?
The solution is going to differ from OS to OS. On Windows, the default browser (i.e. the default handler for the http protocol) can be read from the registry at:
HKEY_CURRENT_USER\Software\Classes\http\shell\open\command\(Default)
Python has a module for dealing with the Windows registry, so you should be able to do:
from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValue
# In Py3, this module is called winreg without the underscore
with OpenKey(HKEY_CURRENT_USER,
r"Software\Classes\http\shell\open\command") as key:
cmd = QueryValue(key, None)
You'll get back a command line string that has a %1 token in it where the URL to be opened should be inserted.
You should probably be using the subprocess module to handle launching the browser; you can retain the browser's process object and kill that exact instance of the browser instead of blindly killing all processes having the same executable name. If I already have my default browser open, I'm going to be pretty cheesed if you just kill it without warning. Of course, some browsers don't support multiple instances; the second instance just passes the URL to the existing process, so you may not be able to kill it anyway.
I would suggest this. Honestly Python should include this in the webbrowser module that unfortunately only does an open bla.html and that breaks anchors on the file:// protocol.
Calling the browser directly however works:
# Setting fallback value
browser_path = shutil.which('open')
osPlatform = platform.system()
if osPlatform == 'Windows':
# Find the default browser by interrogating the registry
try:
from winreg import HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, OpenKey, QueryValueEx
with OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice') as regkey:
# Get the user choice
browser_choice = QueryValueEx(regkey, 'ProgId')[0]
with OpenKey(HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(browser_choice)) as regkey:
# Get the application the user's choice refers to in the application registrations
browser_path_tuple = QueryValueEx(regkey, None)
# This is a bit sketchy and assumes that the path will always be in double quotes
browser_path = browser_path_tuple[0].split('"')[1]
except Exception:
log.error('Failed to look up default browser in system registry. Using fallback value.')

Open a URL in Epiphany from Python Script on RPi2

So I am trying to open a URL in Epiphany WebBrowser [ let's say for example http://www.google.com ] from a python script. My python script is as follows:
import os
string = "DISPLAY=:0 xdg-open http://www.google.com"
os.system(string)
It returns the error: xdg-open: no method available for opening 'http://www.google.com'
However if I type DISPLAY=:0 xdg-open http://www.google.com into LXTerminal is works fine. It also works remotely through SSH.
Any Ideas? Also can someone explain to me why a command works fine in terminal, but not when you try to call them from a Python script using os.system()?
UPDATE -- NEED HELP STILL
NOTE: All files are located in /home/pi
After much frustration, I figured I would give the below method a try. I created a file called google.sh. The code for google.sh s as follows:
#google.sh
DISPLAY=:0 xdg-open http://www.google.com
when I call upon this program using ./google.sh from LXTerminal it works fine! Great so now let's call it from a python script called test.py whose code is as follows:
# test.py
import os
string = "/home/pi/google.sh"
os.system(string)
However for some reason it STILL returns: xdg-open: no method available for opening 'http://www.google.com'
how about this?
the idea, is to open a epiphany window and close it after 5 seconds.
import subprocess
from time import sleep
p = subprocess.Popen("exec epiphany-browser http://yahoo.com", stdout=subprocess.PIPE,shell=True)
sleep(5)
p.kill()
print("done")

Categories