Webbrowser 'directory not found' error - python

I am having a reoccurring error with the webbrowser module on python. Whenever I run this program, I get a multiple errors.
import webbrowser
google_urls = ["www.gmail.com", "www.youtube.com"]
def open_tabs(url_lists):
for url in url_lists:
webbrowser.open_new_tab(url)
def main():
webbrowser.open("www.google.com", new=2, autoraise=False)
open_tabs(google_urls)
main()
These are the errors I get:
/home/garion/Documents/www.youtube.com: No such file or directory (also 2 more, which are the same, except the are for www.google.com and www.gmail.com)
I am using lubuntu, python IDLE 3.5, and Chromium.

webbrowser.open('https://www.youtube.com')
use the https:// in front.

Related

Error "-10814" when opening chrome url with webbrowser.open_new()

I run the following commands and receive execution error.
Here is my code:
import webbrowser
test = "chrome://chrome-urls/"
webbrowser.open_new(test)
Error:
0:37: execution error: An error of type -10814 has occurred. (-10814)
What is my mistake? I use Pycharm on MacOs
Well, it seems there isn't much on this error, but what I could find is that -10814 is a kLSApplicationNotFoundErr. It probably means that the OS launch services can't associate the given URL with a default app to open it, which makes sense since you are trying to open an internal chrome URL. It probably won't throw the same error with standard http/https URLs.
This code works fine for me.
import webbrowser
test = 'https://stackoverflow.com/'
ff = webbrowser.get('google-chrome')
ff.open(test)
But this does not.
import webbrowser
test = 'chrome://chrome-urls/'
ff = webbrowser.get('google-chrome')
ff.open(test)
Maybe you cannot open this type of urls.

Pythons Webbrowser Module Will Never Open a Link in a new Window

I was trying to automate opening multiple user profiles given a list of names on a few different sites but i can not find a way to open a link in a new window meaning i can not sort the different sites i am opening into their own window collection.
here is my code:
import webbrowser
chrome_path="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
firefox_path="C:\\Program Files\\Mozilla Firefox\\Firefox.exe"
strURL = "http://www.python.org"
webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path),1)
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(chrome_path),1)
webbrowser.open(strURL, new=0)
webbrowser.open(strURL, new=1)
webbrowser.open(strURL, new=2)
webbrowser.get('chrome').open(strURL)
webbrowser.get('firefox').open(strURL)
webbrowser.get('chrome').open_new(strURL)
webbrowser.get('firefox').open_new(strURL)
no matter what value i put for new (0, 1, or 2), all that ever happens is it opens a new tab in the last window i clicked on. i have tried all of the other methods that i found in they python documentation for the webbrowser module and everyone online is just saying to use "new=1" or webbroswer.open_new() but neither of those work. and even when i point it at firefox it just goes to chrome.
P.S.
i found a small workaround that i am not totally satisfied with.
import webbrowser
chrome_path = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
chrome_path_NW = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s --new-window"
firefox_path = "C:\\Program Files\\Mozilla Firefox\\Firefox.exe"
strURL = "http://www.python.org"
controller = webbrowser.get(chrome_path)
controllerNW = webbrowser.get(chrome_path_NW)
controllerNW.open(strURL, new=0)
controller.open(strURL, new=1)
controller.open(strURL, new=2)
controller.open("www.youtube.com", new=2)
the important thing to look at would be the "chrome_path" variable. i have changed it so it will run as a command and accept arguments. i found some launch arguments for chromium, here, that seem to work from chrome too. "--new-window" will open a new window and i can then open more tabs in that window but this is a total workaround of pythons module that i am not confident won't break if i am trying to use chrome while running this script. if there is any feature where i could group links together to open in specific windows that would be much more useful to me.
I realise this is a bit late but hopefully i can help someone in the future.
Basically you need to use the subprocess module to open up a new window before you load a new webpage
import subprocess
import time
import webbrowser
subprocess.Popen('open -a /Applications/Google\ Chrome.app --new', shell=True)
time.sleep(0.5) # this is to let the app open before you try to load a new page
webbrowser.open(url)

Building the SeeingWand on Raspberry Pi Zero and have coding issues

This is my first posting, so please forgive any lack of decorum
I am building a SeeingWand as outlined in MagPi issue #71.
I have installed and tested all the HW. Then install the python code, the original; code was python2.7, I have update the code to run under python3, but get a strange error when i run the code:
The system displays that the http module does not have a .client attribute.
The documentation says it does. I have tried .client and .server attributes both give the same error. What am i doing wrong?
I have tried several coding variations and several builds of the raspberry OS (Raspbian) mostly give the same errors
import picamera, http, urllib, base64, json, re
from os import system
from gpiozero import Button
CHANGE {MS_API_KEY} BELOW WITH YOUR MICROSOFT VISION API KEY
ms_api_key = "{MS_API_KEY}"
camera button - this is the BCM number, not the pin number
camera_button = Button(27)
setup camera
camera = picamera.PiCamera()
setup vision API
headers = {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': ms_api_key,
}
params = urllib.parse.urlencode({
'visualFeatures': 'Description',
})
loop forever waiting for button press
while True:
camera_button.wait_for_press()
camera.capture('/tmp/image.jpg')
body = open('/tmp/image.jpg', "rb").read()
try:
conn = http.client.HTTPsConnection('westcentralus.api.cognitive.microsoft.com')
conn.request("POST", "/vision/v1.0/analyze?%s"%params, body, headers)
response = conn.getresponse()
analysis=json.loads(response.read())
image_caption = analysis["description"]["captions"][0]["text"].capitalize()
# validate text before system() call; use subprocess in next version
if re.match("^[a-zA-z ]+$", image_caption):
system('espeak -ven+f3 -k5 -s120 "' + image_caption + '"')
else :
system('espeak -ven+f3 -k5 -s120 "i do not know what i just saw"')
conn.close()
except Exception as e:
print (e.args)
The system displays an error stating that the http module does not have a .client attribute.
The documentation says it does. I have tried .client and .server attributes both give the same error. What am i doing wrong?
Expected results are:
when i push button 1 I expect the camera to take a picture
when i push button 2 i expect to access MSFT Azure to identify the picture using AI
the final output is for the Wand to access the audio hat and describe what the Wand is "looking" at.
try adding an import like this:
import http.client
Edit: http is a Python package. Even if the package contains some modules, it does not automatically import those modules when you import the package, unless the __init__.py for that package does so on your behalf. In the case of http, the __init__.py is empty, so you get nothing gratis just for importing the package.

Cannot run PhantomJS with Flask on Ubuntu VPS

I'm doing a testing unit that requires the tests to be run via web browser. I'm using Ubuntu VPS 14 with LAMP stack installed, mod_wsgi, selenium 2.44 and PhantomJS 1.9. I'm testing with the very simple code first:
from flask import Flask, request
from selenium import webdriver
app = Flask(__name__)
app.debug = True
#app.route("/test")
def test():
url = "http://www.google.com"
driver = webdriver.PhantomJS('./phantomjs')
driver.get(url)
result = driver.page_source
driver.close()
return result
if __name__ == "__main__":
app.run()
The code runs very smoothly on my local Ubuntu, it prints out the google page when I connect to: 127.0.0.1:5000/test . On my Ubuntu VPS, my have my flask already setup and running. Now i use the same code to be the index file (supposed all configs are OK and 'hello world' runs), I have 500 Internal Server Error when connecting to http://xxx.xxx.xxx.xxx/test
Apache log sends out the following error:
... service_args=service_args, log_path=service_log_path File
"/usr/local/lib/python2.7/ddist-packages/selenium/webdriver/phantomjs/service.py",
line 53, in init
self._log = open(log_path, 'w') in > ignored Exception AttributeError: "'Service' object
has no attribute '_log'" in > ignored
I changed the log_path for phatomJS but still have the same problem. However, if I open python console, doing line by line as following:
from selenium import webdriver
br = webdriver.PhantomJS('./phantomjs')
....
I got no error. It took me the whole day to fin the problem but I could't be able to fix it. Any ideas how to solve this problem?
Figure out the problem, current phantomjs and init.py don't have enough permission to manipulate the service.py of ghostdriver. Here is the fix:
Add a new user: "add username", then set "add username sudo"
Login to the new user, make sure every command you run from now on starts with "sudo"
In your flask application where init.py resides, create "ghostdriver.log" and "phantomjs" which is an executable file.
Chmod both of them to 777 : init.py, ghostdriver.log and phantomjs
Set the custom config in init.py for phantomjs:
br = webdriver.PhantomJS(service_log_path='./ghostdriver.log', executable_path='./phantomjs')
That's it, now your selenium + flask + phantomjs is now working correctly.

Call to operating system to open url?

What can I use to call the OS to open a URL in whatever browser the user has as default?
Not worried about cross-OS compatibility; if it works in linux thats enough for me!
Here is how to open the user's default browser with a given url:
import webbrowser
url = "https://www.google.com/"
webbrowser.open(url, new=0, autoraise=True)
Here is the documentation about this functionality. It's part of Python's stdlibs:
http://docs.python.org/library/webbrowser.html
I have tested this successfully on Linux, Ubuntu 10.10.
Personally I really wouldn't use the webbrowser module.
It's a complicated mess of sniffing for particular browsers, which will won't find the user's default browser if they have more than one installed, and won't find a browser if it doesn't know the name of it (eg Chrome).
Better on Windows is simply to use the os.startfile function, which also works on a URL. On OS X, you can use the open system command. On Linux there's xdg-open, a freedesktop.org standard command supported by GNOME, KDE and XFCE.
if sys.platform=='win32':
os.startfile(url)
elif sys.platform=='darwin':
subprocess.Popen(['open', url])
else:
try:
subprocess.Popen(['xdg-open', url])
except OSError:
print 'Please open a browser on: '+url
This will give a better user experience on mainstream platforms. You could fall back to webbrowser on other platforms, perhaps. Though most likely if you're on an obscure/unusual/embedded OS where none of the above work, chances are webbrowser will fail too.
You can use the webbrowser module.
webbrowser.open(url)
Then how about mixing codes of #kobrien and #bobince up:
import subprocess
import webbrowser
import sys
url = 'http://test.com'
if sys.platform == 'darwin': # in case of OS X
subprocess.Popen(['open', url])
else:
webbrowser.open_new_tab(url)
Have a look at the webbrowser module.

Categories

Resources