webbrowser script executes without error, but nothing happens? - python

Im writing a script which is supposed to open different browser with given urls.
When I run it in eclipse it runs the script without errors, but no browsers open. :/
import webbrowser as wb
url_mf = ['https://www.thatsite.com/','http://thatothersite.org/']
url_gc = ['https://www.thatsite.com/','http://thatothersite.org/']
chrome = wb.get('/usr/bin/google-chrome %s')
firefox = wb.get('fierfox %s')
chrome.open(url_gc[1], new=1)
firefox.open(url_mf[1], new=1)
I also have a script using the IEC.py module to open Internet explorer (I need to enter login info and, later, extract horribly unformatted db queries from a site - mechanize & selenium seemed a bit over the top for that?), and that works just fine. But I'm guessing that's like comparing apples and oranges?
import iec
ie= iec.IEController()
ie.Navigate(url_ie[1])
Any help is very much appreciated.

First thing I noticed is the typo on line 5. It should be Firefox instead of fierfox. Second thing, I ran your code in SublimeText 2, I had no problems, I changed the paths because I'm on a windows machine.
The code below opened both Firefox and Chrome.
import webbrowser as wb
url_mf = ['https://www.thatsite.com/','http://www.google.ie/']
url_gc = ['https://www.thatsite.com/','http://www.google.ie/']
chrome = wb.get('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" %s')
firefox = wb.get('"C:/Program Files (x86)/Mozilla Firefox/firefox.exe" %s')
chrome.open(url_gc[1], new=1)
firefox.open(url_mf[1], new=1)
Do you really want to specify which browser the program wants to use ?, I'd suggest using
import webbrowser as wb
urls = ["http://www.google.ie/","http://www.gametrailers.com/"]
for url in urls:
wb.open(url,new=2, autoraise=True)
This would just get your default browser and open each of the links in new tabs.

Related

Blender Python Open Browser With Specific Size And In The Center Of The Screen

I'm writing a blender python plugin which has an integrated connection to an online market, when the user buys a product (3d model) a window needs to open up to make the transaction through PayPal. The code I'm using works ok for that:
import webbrowser
webbrowser.open_new("http://www.paypal.com/buyProductURL")
However the window does not open up in the center of the screen and I also cannot find out how to define the size of the browser window that is being opened.
How can I move the browser window to the center and how can I define its size?
I think this might be what you want:
import webbrowser
browser = ' '.join([
"chrome",
"--chrome-frame",
"--window-size=800,600",
"--window-position=240,80",
"--app=%s &",
])
webbrowser.get(browser).open('http://www.paypal.com/buyProductURL')
The %s parameter is the url used by the module. It's required to call the browser as a command with arguments.
Here are some answers on how to call chrome in the command line.
If you require portability with the same behavior across all browsers it seems to be unattainable to me. I don't think you have an alternative here unless you ship the browser with your code or write more code for browser alternatives like chrome, firefox and opera. I wrote a code where it would work as a popup-like on chrome and chromium and as a tab open on other browsers:
import webbrowser
try_browsers = {
"chrome": [
"chrome",
"--chrome-frame",
"--window-size=800,600",
"--window-position=240,80",
"--app=%s &",
],
}
try_browsers['chromium'] = try_browsers['chrome'][:]
try_browsers['chromium'][0] = 'chromium'
URL = 'http://www.paypal.com/buyProductURL'
for browser in try_browsers.values():
if webbrowser.get(' '.join(browser)).open(URL):
break
else:
webbrowser.open(URL)

Python: How to open map created with folium in browser when running application

I have a very small application written in PyCharm using python3:
import folium
map = folium.Map(location=[58.1, 23.3], zoom_start=10)
map.save('map2.html')
This will create a map2.html which I can access in my browser by using pycharm and the url looks like: http://localhost:63342/iss-country/map2.html?_ijt=dcsefdg8om4ddfovlt5ooq6ro5
How can I automatically open this in my browser? So when I run the application it does not only generate the html page but also visits it immediatley. I found the webbrowser module which can be useful but how do I know the correct localhost url?
I don't see the issue with using the webbrowser module. Just make the file name and path a variable and call the webbrowser open method.
output_file = "map2.html"
map = folium.Map(location=[58.1, 23.3], zoom_start=10)
map.save(output_file)
webbrowser.open(output_file, new=2) # open in new tab

Trying to pass extracted text from Tesseract OCR to custom google search

Having some trouble with a project and hopefully someone can help! I'm trying to take extracted text from tesseract OCR and use that text as the search query of Google Chrome searches. My shell script can extract the text and launch Chrome, but I cant figure out how to send the text to the searchbar of chrome. Below are some pictures of my script. I'm extremely new to coding, so any help is appreciated.
Shell script
echo "Realtime Screen OCR"
while true
do
echo "Waiting for trigger"
read
screencapture -R31,205,420,420 screens.png
tesseract screens.png ocr
OCR=`cat ocr.txt`
python3 launch1.py $OCR
##/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome $OCR
echo "Opened Chrome...waiting for next question"
done
Python Script
import urllib.parse
search_query = input("enter search query")
query_encoded = urllib.parse.quote_plus(search_query)
google_search_url = "http://www.google.com/search?q=" +
format(query_encoded)
import webbrowser
webbrowser.open(google_search_url)
It appears to me that the only step you're missing is grabbing the text in your Python code and passing it into the search query. You can do this using sys. In this example we replace the user-inputted text with retrieving the argument from the command line, assuming that this is what you're trying to do.
import urllib.parse
import sys
search_query = sys.argv[1]
query_encoded = urllib.parse.quote_plus(search_query)
google_search_url = "http://www.google.com/search?q=" +
format(query_encoded)
import webbrowser
webbrowser.open(google_search_url)

Python 2.7 changing default browser for webbrower.open

I am trying to open a page a wrote and saved to a local server. Everything is great but it defaults to opening in IE instead of Chrome. Chrome is my default browser and couldn't find any helpful tips online.
Sample code:
import webbrowser
webbrowser.open('192.168.1.254:1337/SmartFormTest1.php')
Thanks in advance!
Alright, found the issue. My browser was correctly defaulted to chrome, the issue is the webbrowser.py file. Lines 539-563 read:
if sys.platform[:3] == "win":
class WindowsDefault(BaseBrowser):
def open(self, url, new=0, autoraise=True):
try:
os.startfile(url)
except WindowsError:
# [Error 22] No application is associated with the specified
# file for this operation: '<URL>'
return False
else:
return True
_tryorder = []
_browsers = {}
# First try to use the default Windows browser
register("windows-default", WindowsDefault)
# Detect some common Windows browsers, fallback to IE
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"Internet Explorer\\IEXPLORE.EXE")
for browser in ("firefox", "firebird", "seamonkey", "mozilla",
"netscape", "opera", iexplore):
if _iscommand(browser):
register(browser, None, BackgroundBrowser(browse()
All I needed to do was add "chrome" to the list of for browser in (list).
Following the documentation, there are a few directions you can go with this:
Set the environment variable BROWSER
Use webbrowser.get('chrome') to get a controller instance of Chrome, then use that to do your browsing
Check your setup -- are you positive that your default browser is set properly? Does it appear under the "Internet" icon in your Start menu?
In Windows, the following code works for me.
chrome_path = '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" %s'
webbrowser.get(chrome_path).open('google.com')
My browser was correctly defaulted to brave, just change it in the webbrowser.py file. Lines 539-563
In Line 540, just change the OS path to the desired browser you want to use. For Brave just change the path given to the iexplorer variable
like this:
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"BraveSoftware\\Brave-Browser\\Application\\brave.EXE")

Upload a file using WebDriver & PyWinAuto

I have a python script that tries to upload a file from my PC to a web application.
I press via WebDriver the specific upload button in the browser and then a Win7 explorer window opens for me to navigate and select the desired file to upload.
How could I manipulate this window with pywinauto?
optional: could this be done in linux as well (with an appropriate library I suppose) ?
This is my sample code:
wd.find_element_by_css_selector("img.editLecturesButtons.fromVideo").click()
#switch to the lightbox
wd.switch_to_frame(int("1"))
#hit upload
wd.find_element_by_xpath("//*[#id='fileUpload']").click()
#TODO
import os,pywinauto.application
file = os.path.normpath("C:\Users\me\Desktop\image.jpg")
....
I agree with Mark, you should try the Webdriver methods. Regard to pywinauto, code may looks like:
import pywinauto
pwa_app = pywinauto.application.Application()
w_handle = pywinauto.findwindows.find_windows(title=u'Open', class_name='#32770')[0]
window = pwa_app.window_(handle=w_handle)
ctrl = window['Name']
ctrl.SetText(file)
ctrl = window['OK']
ctrl.Click()
This sollution only for Windows, since pywinauto uses win32 api.

Categories