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)
Related
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.
I had try with python with webbrowser.open, but it only work on IE. How to let it open chrome or firefox. I don't want it to open on IE, i wants to be open on Chrome or Firefox. Due to i try many method, but none of them works.
import time
import webbrowser
webbrowser.open('www.google.com')
you need specify your webbrowser's name, detal see webbrowser.get
import webbrowser
webbrowser.open('www.google.com')
a = webbrowser.get('firefox')
a.open('www.google.com') # True
UPDATE
If you have chrome or firefox installed in your computer, do as following:
chrome_path =r'C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chrome.exe' # change to your chrome.exe path
# webbrowser is just call subprocess.Popen, so make sure this work in your cmd firstly
# C:\Users\Administrator>C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chrome.exe www.google.com
# there two way solve your problem
# you have change \ to / in windows
# this seems a bug in browser = shlex.split(browser) in windows
# ['C:UsersAdministratorAppDataLocalGoogleChromeApplicationchrome.exe', '%s']
a = webbrowser.get(r'C:/Users/Administrator/AppData/Local/Google/Chrome/Application/chrome.exe %s')
a.open('www.google.com') #True
# or by register
webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(r'C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chrome.exe'))
a = webbrowser.get('chrome')
a.open('www.google.com') #True
else you can try selenium, it provide much more functions and only need chromedriver.
I am trying to get python to enqueue music files into Winamp.
I have tried the following:
pywinamp
some functions work, but add to playlist doesn't
WACommand
Again some command line switches work, but load file doesn't
Does anyone know some way to get this done? I am not looking for a complete controller for winamp, just a way to push files into the playlist in an already running instance.
I am using winamp 5.63 and windows 7 x64 and python 2.7
Not too sure if this is what you are looking for but I hope it may help...
I found a rough way to do it and that is:
Go to into Winamp, go to options->preferences->file types then check the box that says "Enqueue files on double click" then accept the preferences.
Once that is done the following Python code will put 20 (or how ever many you set the while loop to) songs into the playlist from the given directory.
Also if you didn't want the songs to be random you could assign the path variable to be the file path of whatever file you select
import os
import random
import dircache
i = 0
while i < 20: # change 20 to how ever many songs you want to generate
# set your directory in line bellow
dir = "C:\"
filename = random.choice(dircache.listdir(dir))
path = os.path.join(dir, filename)
os.startfile(path)
i+=1
I'm using Python 3 on Windows 8 64-bit and using pywinamp.py I can add files to playlist and play the file. Here is my code:
# Run winamp.exe
try:
with open(os.devnull, 'wb') as devnull:
devnull = open(os.devnull)
winamp_path = 'C:\\Program Files\\Winamp\\winamp.exe'
p = subprocess.Popen([winamp_path], stdout=devnull, stderr=devnull)
except OSError as e:
# handle the exception
pass
w = Winamp() # class from pywinamp.py
# Wait for app to start
''' For some reason i couldn't access __mainWindowHWND attribute of Winamp class so i added this line in __init__ method of Winamp class: self.wid = self.__mainWindowHWND. This way i know if winamp is open'''
while not w.wid:
w = Winamp()
time.sleep(2)
# Enqueue file in Winamp
w.enqueueFile(filepath.encode('utf-8')) # ctypes needs bytes type
# Get length of winamp playlist and set position on the last track
w.setPlaylistPosition(w.getListLength())
# Play song
w.play()
pywinamp works with python 2.7 x86 properly, but not with python 2.7 x64.
So that.
I'm writing some tests and I'm I'm using the Firefox webdriver with a FirefoxProfile to download a file from an external url, but I need to read such file as soon as it finishes downloading to retrieve some specific data.
I set my profile and driver like this:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList", 2)
fp.set_preference("browser.download.manager.showWhenStarting", False)
fp.set_preference("browser.download.dir", '/some/path/')
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain, application/vnd.ms-excel, text/csv, text/comma-separated-values, application/octet-stream")
ff = webdriver.Firefox(firefox_profile=fp)
Is there some way to know when the file finishes downloading, so that I know when to call the reader function without having to poll the download directory, waiting with time.sleep or using any Firefox add-on?
Thanks for any help :)
You could try hooking the file up to a file object as it downloads to use it like a stream buffer, polling it as it downloads to get the data you need, monitoring for the download completion yourself directly (either by waiting for the file to be of the expected size or by assuming it is complete if there has been no new data added for a certain amount of time).
Edit:
You could try to look at the download tracking db in the profile folder as referenced here. Looks like you can wait for your file to have status 1.
I like to use inotify to watch for these kinds of events. Some example code,
from pyinotify import (
EventsCodes,
ProcessEvent,
Notifier,
WatchManager,
)
class EventManager(ProcessEvent):
def process_IN_CLOSE_WRITE(self, event):
file_path = os.path.join(event.path, event.name)
# do something to file, you might want to wait a second here and
# also test for existence because ff might be making temp files
wm = WatchManager()
notifier = Notifier(wm, EventManager())
wdd = wm.add_watch('/some/path', EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE'], rec=True)
While True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except:
notifier.stop()
raise
The notifier decides which method to call on the event manager based on the name of the event. So in this case we are only watching for IN_CLOSE_WRITE events
It's far from ideal, however with firefox you could check the target folder for the presence of the .part file which is present while it's still downloading (with other browsers you can do something similar).
A while loop will then halt everything while waiting for the download to complete:
import os
def test_for_partfile():
part_file = False
dir = "C:\\Downloads"
filelist = (os.listdir(dir))
for partfile in filelist:
if partfile.endswith('.part'):
part_file = True
return part_file
while test_for_partfile():
time.sleep(15)
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.