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")
Related
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)
Essentially, I'm trying to find the ChromeDriver version without actually opening it. The reason for this is that I want to auto update the driver. I've sorted the code out for updating it.
The issue is that when I intentionally download an unsupported version to check my code works, it says "This driver only supports Chrome Version 86 and you're on 88.001.xyz" etc.
I was wondering if there was any way of reading the 86 from the ChromeDriver executable so that I can recognise it's not equal to 88 (my chrome browser version)? By doing this, it'll trigger a procedure to go and download the correct chromedriver.
I've attached my code for checking the chromedriver version. I've tried headless but I'm sure it doesn't work.
def get_chrome_version():
global browser_version_number
options = Options()
options.headless = True
browser_version_driver = webdriver.Chrome("chromedriver_win32/chromedriver.exe", chrome_options=options)
# browser_version_driver = webdriver.Chrome("chromedriver_win32/chromedriver.exe")
# browser_version_driver.set_window_position(-10000,0)
browser_version_number = (browser_version_driver.capabilities['browserVersion'])
browser_version_number = browser_version_number.split(".")[0]
chromedriverversion = browser_version_driver.capabilities['chrome']['chromedriverVersion'].split('.')[0]
print(browser_version_number)
print(chromedriverversion)
if browser_version_number != chromedriverversion:
update_chrome_version()
browser_version_driver.quit()
you could have your python script make a shell call to execute the command ./chromedriver --version (using the relevant path), then parse the result to find your current installed version.
Alrighty, so I found the solution. It all lied within the exception that was outputted in the terminal. Basically my thinking was to save the exception as string to a variable. Once I could do that, I could split it up and get what was needed from it. This was really easy to do since the ChromeDriver devs had this exception message:
Message: session not created: This version of ChromeDriver only supports Chrome version 86
Current browser version is 88.0.4324.xyz with binary path C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
So I needed to get the 86 to signify the ChromeDriver version and the 88 for the browser version. I've included the code below. If you have any questions, feel free to comment! I'm also aware that I may get crucified for the absolute spaghetti code I've written :). I just want to get something out and then clean up the tomato sauce off my shirt later!!
import logging
logger = logging.Logger('catch_all')
def get_chrome_version():
global browser_version_number
try:
browser_version_driver = webdriver.Chrome("chromedriver_win32/chromedriver.exe")
browser_version_number = (browser_version_driver.capabilities['browserVersion'])
browser_version_number = browser_version_number.split(".")[0]
chromedriverversion = browser_version_driver.capabilities['chrome']['chromedriverVersion'].split('.')[0]
print(browser_version_number)
print(chromedriverversion)
if browser_version_number != chromedriverversion:
update_chrome_version()
browser_version_driver.quit()
###############---------------REALLY IMPORTANT PART BELOW---------------###############
except Exception as e:
e = str(e) # Saves exception to a variable. Most importantly, converts to string to allow me to manipulate it.
print(e)
linesplit = e.split('This version of ChromeDriver only supports Chrome version ')[1]
checking_driverversion = linesplit.split('\n')[0]
print(checking_driverversion) # prints '86' which is my chromedriver right now
checking_browserversion = linesplit.split('\n')[1]
checking_browserversion = checking_browserversion.split('Current browser version is ')[1]
checking_browserversion = checking_browserversion.split('.')[0]
print(checking_browserversion) # prints '88' which is my browser version right now
browser_version_number = checking_browserversion
if checking_browserversion != checking_driverversion:
update_chrome_version()
I just started learning selenium with python
from selenium import webdriver
MY_PROFILE = "D:\\FIREFOX_PROFILE"
FFP = webdriver.FirefoxProfile(MY_PROFILE)
print(FFP.profile_dir)
# OUTPUT: C:\Users\ABC\AppData\Local\Temp\****\***
# But it should be OUTPUT: D:\FIREFOX_PROFILE
DRIVER = webdriver.Firefox(firefox_profile = FFP)
print(FFP.profile_dir)
# OUTPUT: C:\Users\ABC\AppData\Local\Temp\****\***
# But it should be OUTPUT: D:\FIREFOX_PROFILE
I want to save my profile somewhere so that I can use it later on.
I also tried creating RUN -> firefox.exe -p and creating a new profile (I can't use the created profile). Nothing works.
I am using:
Selenium Version: 2.53.6
Python Version: 3.4.4
Firefox Version: Various(49.0.2, 45, 38 etc)
I searched in Google but I can't solve it. Is there any way to save the profile?
You need to take help of os module in python
import os
there you get functions (like .getcwd() ) to described in Files and Directories.
then use,
p = webdriver.FirefoxProfile()
p.set_preference('browser.download.folderList', 2 )
p.set_preference('browser.download.manager.showWhenStarting', false)
p.set_preference('browser.download.dir', os.getcwd())
p.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv/xls')
driver = webdriver.Firefox(p)
in short you can do so,
profile.set_preference("browser.helperApps.neverAsk.openFile","text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml")
possible duplicate of Setting selenium to use custom profile, but it keeps opening with default
Looking to use RSelenium and Tor using my Linux machine to return the Tor IP (w/Firefox as Tor Browser). This is doable with Python, but having trouble with it in R. Can anybody get this to work? Perhaps you can share your solution in either Windows / Linux.
# library(devtools)
# devtools::install_github("ropensci/RSelenium")
library(RSelenium)
RSelenium::checkForServer()
RSelenium::startServer()
binaryExtension <- paste0(Sys.getenv('HOME'),"/Desktop/tor-browser_en-US/Browser/firefox")
remDr <- remoteDriver(dir = binaryExtention)
remDr$open()
remDr$navigate("http://myexternalip.com/raw")
remDr$quit()
The error Error in callSuper(...) : object 'binaryExtention' not found is being returned.
For community reference, this Selenium code works in Windows using Python3:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from os.path import expanduser # Finds user's user name on Windows
# Substring inserted to overcome r requirement in FirefoxBinary
binary = FirefoxBinary(r"%s\\Desktop\\Tor Browser\\Browser\\firefox.exe" % (expanduser("~")))
profile = FirefoxProfile(r"%s\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default" % (expanduser("~")))
driver = webdriver.Firefox(profile, binary)
driver.get('http://myexternalip.com/raw')
html = driver.page_source
soup = BeautifulSoup(html, "lxml") # lxml needed
# driver.close()
# line.strip('\n')
"Current Tor IP: " + soup.text.strip('\n')
# Based in part on
# http://stackoverflow.com/questions/13960326/how-can-i-parse-a-website-using-selenium-and-beautifulsoup-in-python
# http://stackoverflow.com/questions/34316878/python-selenium-binding-with-tor-browser
# http://stackoverflow.com/questions/3367288/insert-variable-values-into-a-string-in-python
Something like the following should work:
browserP <- paste0(Sys.getenv('HOME'),"/Desktop/tor-browser_en-US/Browser/firefox")
jArg <- paste0("-Dwebdriver.firefox.bin='", browserP, "'")
selServ <- RSelenium::startServer(javaargs = jArg)
UPDATE:
This worked for me on windows. Firstly run the beta version:
checkForServer(update = TRUE, beta = TRUE, rename = FALSE)
Next open a version of the tor browser manually.
library(RSelenium)
browserP <- "C:/Users/john/Desktop/Tor Browser/Browser/firefox.exe"
jArg <- paste0("-Dwebdriver.firefox.bin=\"", browserP, "\"")
pLoc <- "C:/Users/john/Desktop/Tor Browser/Browser/TorBrowser/Data/Browser/profile.meek-http-helper/"
jArg <- c(jArg, paste0("-Dwebdriver.firefox.profile=\"", pLoc, "\""))
selServ <- RSelenium::startServer(javaargs = jArg)
remDr <- remoteDriver(extraCapabilities = list(marionette = TRUE))
remDr$open()
remDr$navigate("https://check.torproject.org/")
> remDr$getTitle()
[[1]]
[1] "Congratulations. This browser is configured to use Tor."
This works in MacOS Sierra.
First you need to configure both the Firefox and Tor browser Manual Proxy.
Go to your Preferences>Advanced>Network>Settings
Set SOCKS Host: 127.0.0.1 Port:9150 Check -> on SOCKS v5 in the browser menu bar.
You will also need to have Tor Browser open whilst running the R script in Rstudio ....otherwise you will get a message in the firefox browser "The proxy server is refusing connections"
You will also need to copy the name of your firefox profile in the script profile-name
Open Finder and got to /Users/username/Library/Application Support/Firefox/Profiles/profile-name
My R test script
require(RSelenium)
fprof <- getFirefoxProfile("/Users/**username**/Library/Application\ Support/Firefox/Profiles/nfqudbv2.default-1484451212373",useBase=TRUE)
remDrv <- remoteDriver( browserName = "firefox"
, extraCapabilities = fprof)
remDrv$open()
remDrv$navigate("https://check.torproject.org/")
This will open an instance of the Firefox browser with the message
"Congratulations. This browser is configured to use Tor."
Caveat: I have not tested extensively, but it seems to work.
Relying on some ideas from #Ashley72 but avoiding manual setups and copying (as well as now defunct functions from Rselenium needed for the solution from #jdharrison) and some ideas from https://indranilgayen.wordpress.com/2016/10/24/make-rselenium-work-with-r/ adjust the following profile options (I usually adjust a number of other options, but they do not seem relevant for the question):
fprof <- makeFirefoxProfile(list(network.proxy.socks = "127.0.0.1", # for proxy settings specify the proxy host IP
network.proxy.socks_port = 9150L, # proxy port. Last character "L" for specifying integer is very important and if not specified it will not have any impact
network.proxy.type = 1L, # 1 for manual and 2 for automatic configuration script. here also "L" is important
network.proxy.socks_version=5L, #ditto
network.proxy.socks_remote_dns=TRUE))
Then you start the server as usual:
rD <- rsDriver(port = 4445L, browser = "firefox", version = "latest", geckover = "latest", iedrver = NULL, phantomver = "2.1.1",
verbose = TRUE, check = TRUE, extraCapabilities = fprof) # works for selenium server: 3.3.1 and geckover: 0.15.0; Firefox: 52
remDr <- rD[["client"]]
remDr <- rD$client
remDr$navigate("https://check.torproject.org/") # should confirm tor is setup
remDr$navigate("http://whatismyip.org/") # should confirm tor is setup
As you see, I have not made changes to the marionette option. I have no idea what the implications might be. Please comment.
EDIT: the Tor Browser has to be up and running, it seems. Otherwise, the browser opened by Rselenium gives an error "proxy server refusing connection."
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.