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
Related
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'm currently trying to write a script (to plug in to a Django project) to take a screenshot of a full page of a website using Selenium.
Everything seems to be running OK - the path (fullimsavepath) builds OK (hence the print statement to output so I can see), selenium doesn't report any errors, and the script exits fine. However,
when I look for the actual screenshot in the path provided, it doesn't exist there. What am I doing wrong? Is it something to do with relative vs. absolute paths?
Running Python 3.8 on Windows inside pipenv.
Code:
import time
import os
from sitehawk.settings import BASE_DIR
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from datetime import datetime, date
def takescreenshot(url='http://www.google.com', filename='testpng1'):
options = webdriver.ChromeOptions()
options.headless = True
# Need to replace executable path with environment variable or similar for production?
# At the moment it's an absolute path to the driver
driver = webdriver.Chrome(options=options,executable_path=r'C:/Users/gapbr/Documents/dev/sitehawk/sitehawk-project/screenshots/driver/chromedriver.exe')
driver.get(url)
# Set the path where the image should be saved
actualdate = datetime.now()
yr = actualdate.strftime('%Y')
mn = actualdate.strftime('%m')
filepng = filename+'.png'
fullimsavepath = os.path.join(BASE_DIR,'screenshots','captured-files',yr,mn,filepng)
print(fullimsavepath)
# Take the screenshot
S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X)
driver.set_window_size(S('Width'),S('Height')) # May need manual adjustment
driver.find_element_by_tag_name('body').screenshot(fullimsavepath)
driver.quit()
Maybe Python have doubling of literals like Java does. Try to double your slashes in path like this:
driver = webdriver.Chrome(options=options,executable_path=r'C://Users/gapbr//Documents//dev//sitehawk//sitehawk-project//screenshots//driver//chromedriver.exe')
I have very little knowledge of python. But, for your reference, I have used the below code in my C# project to take a screenshot. I hope you get some ideas from this:
static public void getCapture(string No = "1")
{
//Screenshot
Screenshot ss = ((ITakesScreenshot)Tests.driver).GetScreenshot();
DateTime dt = DateTime.Now;
//Saving_the_screenshot_with_a_filename
var title = dt.ToString("yyyyMMddHHmm") + "_" + No + ".png";
string file = System.IO.Path.Combine(appSettings.Settings["ScreenShotPath"].Value);
if (string.IsNullOrEmpty(file))
{
file = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
}
ss.SaveAsFile(file + #"\" + title);
}
I am running a test with Selenium (Python) remotely on Browserstack Automate.
Goal: I want to start a session on Browserstack, with an existing Chrome profile logged in.
-- Underlying goal: I am trying to access Whatsapp Web without having to scan the QR code every single time. (Building an automated Whatsapp service)
So it would be ok to have a new profile made the first time - scan the QR code once and then re-use that profile afterwards.
Method: I try to use Chrome Options, and specify an argument for user-data-dir. This was inspired by several other StackOverflow answers.
Code:
desired_caps = {
'browser': 'Chrome',
'browser_version': '69.0 beta',
'os': 'Windows',
'os_version': '10',
'resolution': '1024x768',
'browserstack.debug': 'true',
}
desired_caps['browserstack.local'] = True
desired_caps['chromeOptions'] = {}
desired_caps['chromeOptions']['args'] = [r'--user-data-dir=C:\Users\gille\AppData\Local\Google\Chrome\User Data']
driver = webdriver.Remote(command_executor='http://MYBROWSERSTACKHUB', desired_capabilities=desired_caps)
I am trying to run this on Browserstack (locally), but I am getting the following error when running:
"Could not initialize class org.openqa.selenium.os.Kernel32"
See image with Browserstack error
I have tried specifying a new random profile that did not exist yet, e.g.:
desired_caps['chromeOptions']['args'] = [r'--user-data-dir=C:\Users\gille\AppData\Local\Google\Chrome\User Data\ProfileXXX']
But the same error pops up.
(I have also tried other methods that did not work for me:
- Saving and re-loading cookies
- Changing the session_id and session_url (does not work on Browserstack) )
I feel that:
- or this could be a problem with Browserstack,
- or I am including the wrong path for user-data-dir, and should go with a different, e.g. chrome_options.add_argument("user-data-dir=" + os.path.dirname(sys.argv[0])
But I am unfamiliar with the last one - So I am unsure what the next step to take is.
Do you have any advice?
Use the caps as below:
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data");
caps.setCapability(ChromeOptions.CAPABILITY, options);
driver = new RemoteWebDriver(new URL(CloudConfiguration.URL), caps);
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")
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.