Python3.1 - Open Opera - python

I have no idea why this won't work....I'm trying to open opera but it says cannot find runnable browser.
op = webbrowser.get('C:\\Program Files\\Opera\\opera.exe')
op.open_new_tab('http://www.stackoverflow.com')
op.open_new_tab('http://www.stackoverflow.com')

The name parameter should just be 'opera':
op = webbrowser.get('opera')
Make sure you have installed Opera on your computer, and that the executable opera.exe is in the path.
>>> import webbrowser
>>> webbrowser.get('opera')
<webbrowser.BackgroundBrowser object at 0x02095490>
See the table of allowed values for the name parameter in the documentation.
If you want to specify the exact path to the executable (which by the way is a bad idea if you want your application to be portable) then you can specify the command line as follows:
op = webbrowser.get(r'C:\\Program Files\\Opera\\opera.exe %s')

As far as I know, you cannot provide a specific filepath for the browser you want to associate with the webbrowser object. You need to just provide one of a few built-in names. The one you want here is "opera" - see http://docs.python.org/py3k/library/webbrowser.html for details.

You should try to set the browser path to BROWSER environment variable.
Here's how to do it in Windows (which you are apparently using):
http://vlaurie.com/computers2/Articles/environment.htm

Related

Is there a way to get the default browser in Python?

I want a way to find the default browser in Python. I've seen https://docs.python.org/3.8/library/webbrowser.html
and there might be a way of converting a webbrowser instance which I do not know.
Does anybody know how I could go about doing that?
Also, I'm using Windows - it doesn't need to work for Mac or Ubuntu.
Edit:
I've already tried this website and it gives me an error saying that 'the file path does not exist'.
Additionally, I don't want to open a tab in the default browser, I just want the name.
Edit #2:
The following code works but returns Internet Explorer instead of my actual default which is Chrome.
from winreg import*
with OpenKey(HKEY_CLASSES_ROOT,r"http\\shell\\open\\command") as key:
cmd = QueryValue(key, None)
I have figured it out. I'm pretty sure this only works on Windows, but here's the code:
from winreg import *
with OpenKey(HKEY_CURRENT_USER, r"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice") as key:
browser = QueryValueEx(key, 'Progid')[0]
It will return ChromeHTML for Chrome, FirefoxURL for Firefox, and IE.HTTP for Internet Explorer.
You can try this
import webbrowser
default_browser = webbrowser.get()
default_browser_name = default_browser.name
default_browser_basename = default_browser.basename
As the docs say
webbrowser.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.

Can't take screenshot using selenium

Just met a strange problem while running selenium to take the screenshot of web page, below is part of my code:
url = "http://acme.com/licensemaker/licensemaker.cgi?state=California"
driver = webdriver.PhantomJS()
driver.maximize_window()
elem = driver.get(url)
elem = \
driver.find_element_by_xpath
('/html/body/form/center/div/table/tbody/tr[2]/td/input[2]')
elem.send_keys(comb)
driver.find_element_by_xpath
('/html/body/form/center/div/table/tbody/tr[2]/td/input[3]').click()
driver.save_screenshot('../screenshots/1.png')
print('ok')
img = driver.find_element_by_xpath('/html/body/center[1]/div/a/img')
location = img.location
size = img.size
print(size)
I try both PhantomJS and Safari driver neither can they save the screenshot, but I can get the output of both 'ok' and the value of 'location'.
I don't understand why I can't save the screenshot.
Saving the file via absolute path failed but only name worked. I use the same version of Selenium last year it worked with relative path, what happened?
The result of save_screenshot() is True.
OS: macOS Sierra 10.12.5
Interpreter: 2.7.12(/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7)
plus, I'm using Pyenv, and my Pyenv global is 'system'.
You have to consider the fact that, while invoking save_screenshot() you have to mention the full path you wish to save your screenshot to. This should end with a .png extension. As per your case, you may consider to create a directory by the name "screenshots" within your project space through your IDE or manually. In your code mention the path as:
driver.save_screenshot('/screenshots/123.png')
You can use below function for relative path as absolute path is not a good idea to add in script
Import
import sys, os
Use code as below :
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'Screenshots'+ os.sep)
driver.get_screenshot_as_file(screenshotpath+"testPngFunction.png")
make sure you create folder where .py file is present.
os.path.join also prevent you to run your script in cross platform like : unix and windows. It will generate path seprator as per OS in runtime. It is similer like File.separtor in java

%USERPROFILE% env variable for python

I am writing a script in Python 2.7.
It needs to be able to go whoever the current users profile in Windows.
This is the variable and function I currently have:
import os
desired_paths = os.path.expanduser('HOME'\"My Documents")
I do have doubts that this expanduser will work though. I tried looking for Windows Env Variables to in Python to hopefully find a list and know what to convert it to. Either such tool doesn't exist or I am just not using the right search terms since I am still pretty new and learning.
You can access environment variables via the os.environ mapping:
import os
print(os.environ['USERPROFILE'])
This will work in Windows. For another OS, you'd need the appropriate environment variable.
Also, the way to concatenate strings in Python is with + signs, so this:
os.path.expanduser('HOME'\"My Documents")
^^^^^^^^^^^^^^^^^^^^^
should probably be something else. But to concatenate paths you should be more careful, and probably want to use something like:
os.sep.join(<your path parts>)
# or
os.path.join(<your path parts>)
(There is a slight distinction between the two)
If you want the My Documents directory of the current user, you might try something like:
docs = os.path.join(os.environ['USERPROFILE'], "My Documents")
Alternatively, using expanduser:
docs = os.path.expanduser(os.sep.join(["~","My Documents"]))
Lastly, to see what environment variables are set, you can do something like:
print(os.environ.keys())
(In reference to finding a list of what environment vars are set)
Going by os.path.expanduser , using a ~ would seem more reliable than using 'HOME'.

python's webbrowser launches IE, instead of default browser, on Windows relative path

I'm attempting to launch a local html file from python in the default browser (right now my default is Google Chrome if I double-click on a .html file, Chrome launches.)
When I use python's webbrowser.open(), IE launches instead, with a blank address bar.
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import webbrowser
>>> filename = 'test.html'
>>> webbrowser.open('file://'+filename)
True
>>> print(webbrowser.get().__class__.__name__)
WindowsDefault
I've checked my default programs and they look correct. I'm on Win 7 SP1. Why is Chrome not launching?
Update: The code will be running on unknown OS's and machines, so hardcoding or registering browsers or path updates are not options. I'm thinking that parsing the url for file:// and then doing an os.path.exists check and os.path.realpath might be the answer.
My main issue was a bad URL by attempting prepend file:// to a relative path. It can be fixed with this:
webbrowser.open('file://' + os.path.realpath(filename))
Using webbrowser.open will try multiple methods until one "succeeds", which is a loose definition.
The WindowsDefault class calls os.startfile() which fails and returns False. I can verify that by entering the URL in the windows run command and seeing an error message rather than a browser.
Both GenericBrowser and BackgroundBrowser will call subprocess.Popen() with an exe which will succeed, even with a bad URL, and return True. IE gives no indication of the issue, all other browsers have a nice messages saying they can't find the file.
GenericBrowser is set by the environment variable BROWSER and is first.
WindowsDefault is second.
BackgroundBrowser is last and includes the fall back IE if nothing else works.
Here is my original setup:
>>> import webbrowser
>>> webbrowser._tryorder
['windows-default',
'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']
>>> webbrowser._browsers.items()
[('windows-default', [<class 'webbrowser.WindowsDefault'>, None]),
('c:\\program files\\internet explorer\\iexplore.exe', [None, <webbrowser.BackgroundBrowser object at 0x00000000022E3898>])]
>>>
Here is my setup after modifiying the environment variables:
C:>path=C:\Program Files (x86)\Mozilla Firefox;%path%
C:>set BROWSER=C:\Users\Scott\AppData\Local\Google\Chrome\Application\chrome.exe
C:>python
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import webbrowser
>>> webbrowser._tryorder
['C:\\Users\\Scott\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe',
'windows-default',
'firefox',
'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']
>>> webbrowser._browsers.items()
[('windows-default', [<class 'webbrowser.WindowsDefault'>, None]),
('c:\\program files\\internet explorer\\iexplore.exe',[None, <webbrowser.BackgroundBrowser object at 0x000000000235E828>]),
('firefox', [None, <webbrowser.BackgroundBrowser object at 0x000000000235E780>]),
('c:\\users\\scott\\appdata\\local\\google\\chrome\\application\\chrome.exe', [None, <webbrowser.GenericBrowser object at 0x000000000235E8D0>])]
>>>
The webbrowser._tryorder gives the list of browsers tried. Registering chrome or adding a BROWSER env var or modifiying my path all would have gotten me the correct browser with a better error message.
Thanks for the help guys, I couldn't have solved this without your ideas.
You can use get(name) to use a specific browser.
You'll need to register the Chrome webbrowser, as it doesn't seem to be one of the predefined browser types, and then you should be able to do this:
webbrowser.get('chrome').open('http://www.google.com')
Update:
Actually, you might be able to just one of the following:
webbrowser.get('windows-default').open('http://www.google.com')
webbrowser.get('macosx').open('http://www.google.com')
The docs show no predefined defaults for Linux.
This opened a new Chrome tab for me, and it's still OS-independent:
webbrowser.get().open('http://www.google.com')
What's odd is that without the get() call, it still uses IE. This looks like a bug with a simple workaround.
Using Windows 10, in short, everything that does not include a full URL in the https://example.com format is opened in IE for me. For example, if I say
webbrowser.open("https://www.example.com")
it will open a new tab in Chrome, while
webbrowser.open("example.com")
will open IE. Any .get() will cause it to not open a browser at all.
Kind of weird behaviour, but I can see that this is a complex thing do implement and likely the OS is to blame for this behavior.
The webbrowser module is supposed to use the default browser, so this might be a bug. On the other hand, use this explanation from the docs to troubleshoot your problem:
If the environment variable BROWSER
exists, it is interpreted to override
the platform default list of browsers,
as a os.pathsep-separated list of
browsers to try in order. When the
value of a list part contains the
string %s, then it is interpreted as a
literal browser command line to be
used with the argument URL substituted
for %s; if the part does not contain
%s, it is simply interpreted as the
name of the browser to launch.
Looking at the module source code, it first tries to use the Windows default browser but if it doesn't work, it searches for common browser names that are commands, ie. that are in the PATH variable. Try adding the location of your web browser to your PATH.
I have the same problem with firefox. http://www.google.com is opened in ff while file:///test.html is opened in IE.
webbrowser doc says:
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.
What worked for me with Python 3.6, Windows 10, was using the register() function with BackgroundBrowser, to sign in my desired browser:
import webbrowser
# Register your preferable browser
browser_path = 'C:/path/to/opera.exe'
webbrowser.register('opera', None, webbrowser.BackgroundBrowser(browser_path))
# Get an instance and launch your file
browser = webbrowser.get('opera')
browser.open('html_file')
Bonus observation -
webbrowser also has a GenericBrowser class.
Looking at the source, seems BackgroundBrowser uses start_new_session when calling subprocess.Popen(), whereas GenericBrowser does not.
I'm not aware of that flag's exact functionality.
Practically however, using BackgroundBrowser switches to the browser window, while GenericBrowser just opens the tab, but doesn't switch.
This problem appears for me only with file:/// protocol URLs, which are probably not registered to chrome, so os.startfile() (which is the first thing webbrowser.open tries on Windows) opens them in Internet Explorer. I don't think putting your other browser in the PATH will help, since os.startfile() still gets invoked before even trying the browsers in the path.
What you can do, is to check the default browser for http:// in the registry (for instance, by checking the registry key HKEY_CLASSES_ROOT\http\shell\open\command) and use that one for file:/// URLs. Not pretty, but it should work.
import _winreg
import webbrowser
import shlex
import subprocess
def win_browser_open(url):
if url.startswith('file:///'):
browser = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, r'http\shell\open\command')
browser = browser.replace('%1', url)
subprocess.Popen(shlex.split(browser))
else:
webbrowser.open(url)
Use this:
import webbrowser
webbrowser.get('windows-default').open('http://www.google.com')
since all answers did not solve this/my issue, this way worked for me... (windows)
commands needs to be in a list, not in a single string! (in this case, "start", "filepath"), also shell needs to be True (windows)
import subprocess
subprocess.Popen(['start', 'C:/Users/User/Desktop/convert_report.html'], shell=True)
It seems that webbrowser module couldn't find filename in cwd because you opened the program by shortcut or terminal, so cwd is different from the program's directory.
In that case, you have to convert the path into the absolute path of the program's directory when giving a path to webbrowser.open function.
The program's path is stored as __file__ global constant.
You can fix like that:
webbrowser.open(os.path.join(__file__, '..', filename))
I fixed the same problem by this solution.
Add a BROWSER variable to your system variables and put path of your default browser.
I just had the same issue of web pages suddenly opening with Internet Explorer, which only started after installing Visual Studio 2017. My guess is that VS2017 installed its own version of IE.
My program was opening websites using webbrowser.open(url), but I had stripped the 'https://' protocol from the beginning of each URL. Now, by making sure that all URLs have the 'https://' protocol at the beginning, the issue goes away and the pages are once again opened in Chrome (my Windows default browser).

How to find the real user home directory using python?

I see that if we change the HOME (linux) or USERPROFILE (windows) environmental variable and run a python script, it returns the new value as the user home when I try
os.environ['HOME']
os.exp
Is there any way to find the real user home directory without relying on the environmental variable?
edit:
Here is a way to find userhome in windows by reading in the registry,
http://mail.python.org/pipermail/python-win32/2008-January/006677.html
edit:
One way to find windows home using pywin32,
from win32com.shell import shell,shellcon
home = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0)
I think os.path.expanduser(path) could be helpful.
On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.
On Unix, an initial ~ is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd. An initial ~user is looked up directly in the password directory.
On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.
If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.
So you could just do:
os.path.expanduser('~user')
from pathlib import Path
str(Path.home())
works in Python 3.5 and above. Path.home() returns a Path object providing an API I find very useful.
I think os.path.expanduser(path) is the best answer to your question, but there's an alternative that may be worth mentioning in the Unix world: the pwd package. e.g.
import os, pwd
pwd.getpwuid(os.getuid()).pw_dir
For windows;
import os
homepath = os.path.expanduser(os.getenv('USERPROFILE'))
will give you a handle to current user's home directory and
filepath = os.path.expanduser(os.getenv('USERPROFILE'))+'\\Documents\\myfile.txt'
will give you a handle to below file;
C:\Users\urUserName\Documents\myfile.txt
home_folder = os.getenv('HOME')
This should work on Windows and Mac OS too, works well on Linux.
Really, a change in environment variable indicates that the home must be changed. So every program/script should have the new home in context; also the consequences are up to the person who changed it.
I would still stick with
home = os.getenv('USERPROFILE') or os.getenv('HOME')
what exactly is required?
I realize that this is an old question that has been answered but I thought I would add my two cents. The accepted answer was not working for me. I needed to find the user directory and I wanted it to work with and without sudo. In Linux, my user directory is "/home/someuser" but my root directory is "/root/". However, on my Mac, the user directory is "/Users/someuser". Here is what I ended up doing:
_USERNAME = os.getenv("SUDO_USER") or os.getenv("USER")
_HOME = os.path.expanduser('~'+_USERNAME)
This worked both with and without sudo on Mac and Linux.
get (translated) user folder names on Linux:
from gi.repository import GLib
docs = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOCUMENTS)
desktop = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DESKTOP)
pics = GLib.get_user_special_dir(GLib.USER_DIRECTORY_PICTURES)
videos = GLib.get_user_special_dir(GLib.USER_DIRECTORY_VIDEOS)
music = GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC)
downloads = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)
public = GLib.get_user_special_dir(GLib.USER_DIRECTORY_PUBLIC_SHARE)
templates = GLib.get_user_special_dir(GLib.USER_DIRECTORY_TEMPLATES)
print(docs)
print(desktop)
print(pics)
print(videos)
print(music)
print(downloads)
print(public)
print(templates)
On Linux and other UNIXoids you can always take a peek in /etc/passwd. The home directory is the sixth colon-separated field in there. No idea on how to do better than the environment variable on Windows though. There'll be a system call for it, but if it's available from Python, ...

Categories

Resources