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);
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)
I'm trying to emulate 2 actions on a Genymotion emulator using Appium:
Go to a specific URL, the website then redirects to the Google Play Store.
Press "INSTALL" on that Google Play Store screen.
I have managed to get the URL, but when I try to start a driver for the Google Play app, it relaunches the app, which I don't want. I need to emulate a click on the INSTALL button right after I get redirected to Google Play. I have looked into running parallel tests, but it seem to launch the app for every test.
This is my code. Any help would be much appreciated!
from appium import webdriver
desired_caps_web = dict(
platformName='Android',
platformVersion='8',
deviceName='Google Pixel',
automationName='UiAutomator1',
browserName='Chrome',
chromedriverExecutable='C:\\Users\\Khoa_Ngo\\node_modules\\appium-chromedriver\\chromedriver\\win\\chromedriver.exe')
driver_web = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps_web)
driver_web.get('https://someURL.com')
desired_caps_vending = dict(
platformName='Android',
platformVersion='8',
deviceName='Google Pixel',
automationName='UiAutomator1',
app='/Users/Khoa_Ngo/Google Play Store.apk', #This is bit of a workaround because I kept running into problems about intent action.
appPackage='com.android.vending',
)
driver_vending = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps_vending)
driver_vending.find_elements_by_xpath("//*[contains(#id, 'install')]").click() #Not working
Also how should I emulate the click (last line in code block)?
Add capability autoLaunch=false to desired capabilities.
autoLaunch Initializing the app under test automatically. Appium does not install/launch the app under test if this is false. Defaults to true
Description from: http://appium.io/docs/en/writing-running-appium/caps/#android-only
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
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")
I have some JavaScript from a 3rd party vendor that is initiating an image request. I would like to figure out the URI of this image request.
I can load the page in my browser, and then monitor "Live HTTP Headers" or "Tamper Data" in order to figure out the image request URI, but I would prefer to create a command line process to do this.
My intuition is that it might be possible using python + qtwebkit, but perhaps there is a better way.
To clarify: I might have this (overly simplified code).
<script>
suffix = magicNumberFunctionIDontHaveAccessTo();
url = "http://foobar.com/function?parameter=" + suffix
img = document.createElement('img'); img.src=url; document.all.body.appendChild(img);
</script>
Then once the page is loaded, I can go figure out the url by sniffing the packets. But I can't just figure it out from the source, because I can't predict the outcome of magicNumberFunction...().
Any help would be muchly appreciated!
Thank you.
The simplest thing to do might be to use something like HtmlUnit and skip a real browser entirely. By using Rhino, it can evaluate JavaScript and likely be used to extract that URL out.
That said, if you can't get that working, try out Selenium RC and use the captureNetworkTraffic command (which requires the Selenium instant be started with an option of captureNetworkTraffic=true). This will launch Firefox with a proxy configured and then let you pull the request info back out as JSON/XML/plain text. Then you can parse that content and get what you want.
Try out the instant test tool that my company offers. If the data you're looking for is in our results (after you click View Details), you'll be able to get it from Selenium. I know, since I wrote the captureNetworkTraffic API for Selenium for my company, BrowserMob.
I would pick any one of the many http proxy servers written in Python -- probably one of the simplest ones at the very top of the list -- and tweak it to record all URLs requested (as well as proxy-serve them) e.g. appending them to a text file -- without loss of generality, call that text file 'XXX.txt'.
Now all you need is a script that: starts the proxy server in question; starts Firefox (or whatever) on your main desired URL with the proxy in question set as your proxy (see e.g. this SO question for how), though I'm sure other browsers would work just as well; waits a bit (e.g. until the proxy's XXX.txt file has not been altered for more than N seconds); reads XXX.txt to extract only the URLs you care about and record them wherever you wish; turns down the proxy and Firefox processes.
I think this will be much faster to put in place and make work correctly, for your specific requirements, than any more general solution based on qtwebkit, selenium, or other "automation kits".
Use Firebug Firefox plugin. It will show you all requests in real time and you can even debug the JS in your Browser or run it step-by-step.
Ultimately, I did it in python, using Selenium-RC. This solution requires the python files for selenium-rc, and you need to start the java server ("java -jar selenium-server.jar")
from selenium import selenium
import unittest
import lxml.html
class TestMyDomain(unittest.TestCase):
def setUp(self):
self.selenium = selenium("localhost", \
4444, "*firefox", "http://www.MyDomain.com")
self.selenium.start()
def test_mydomain(self):
htmldoc = open('site-list.html').read()
url_list = [link for (element, attribute,link,pos) in lxml.html.iterlinks(htmldoc)]
for url in url_list:
try:
sel = self.selenium
sel.open(url)
sel.select_window("null")
js_code = '''
myDomainWindow = this.browserbot.getUserWindow();
for(obj in myDomainWindow) {
/* This code grabs the OMNITURE tracking pixel img */
if ((obj.substring(0,4) == 's_i_') && (myDomainWindow[obj].src)) {
var ret = myDomainWindow[obj].src;
}
}
ret;
'''
omniture_url = sel.get_eval(js_code) #parse&process this however you want
except Exception, e:
print 'We ran into an error: %s' % (e,)
self.assertEqual("expectedValue", observedValue)
def tearDown(self):
self.selenium.stop()
if __name__ == "__main__":
unittest.main()
Why can't you just read suffix, or url for that matter? Is the image loaded in an iframe or in your page?
If it is loaded in your page, then this may be a dirty hack (substitute document.body for whatever element is considered):
var ac = document.body.appendChild;
var sources = [];
document.body.appendChild = function(child) {
if (/^img$/i.test(child.tagName)) {
sources.push(child.getAttribute('src'));
}
ac(child);
}