Selenoid - Emulating mobile in ChromeDriver / Python - python

I try to set experimental_option on ChromeDriver by Selenoid UI. I tried a lot of cases but neither works, usually, I see a normal browser without mobile emulation in local Selenoid UI or browser is set as unknown when I try another way and I don't have a capabilities dictionary.
My code now, which doesn't work correctly:
capabilities = {
"browserName": "chrome",
"version": "80.0",
"enableVNC": True,
"enableVideo": video,
'screenResolution': "1920x1080",
"chromeOptions": {
"mobileEmulation": {
"deviceName": "Nexus 5"
}
}
}
context.browser = webdriver.Remote(
command_executor="http://selenoid:4444/wd/hub",
desired_capabilities=capabilities)
Maybe somebody knows how to set experimental options in the chrome image in Selenoid UI?

Related

Open chrome new tab in Selenium automated chrome

I'm creating a automated online banking balance check for my mother that's not really good at computer, I've stuck at the part that i want to open pdf file that already automated dowload in local pc then open in selenium automated chrome , is there anyway to do that , Thank you.
with normal webbrowser.open, it only open the chrome not the selenium automated chrome
import webbrowser
file_ = 'C:\\Users\\user\\Downloads\\MASTERCARD PLATINUM'+month_year+".pdf"
webbrowser.open_new_tab("https://www.google.com")
To handle a PDF document in Selenium test automation, we can use a java library called PDFBox
public void verifyContentInPDf() {
//specify the url of the pdf file
String url ="http://www.pdf995.com/samples/pdf.pdf";
driver.get(url);
try {
String pdfContent = readPdfContent(url);
Assert.assertTrue(pdfContent.contains("The Pdf995 Suite offers the following features"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
For Python you can follow this link

I cannot get Chrome to default to saving as a PDF when using Selenium

I'm trying to save some web pages to PDF using Python, Selenium, and Chrome, and I can't get the printer to default to Chrome's built-in "save as PDF" option.
I have found examples of how to do this in various places online, including in questions people have asked on Stack Overflow, but they way they're all implementing it doesn't work and I'm not sure if something has changed in more recent versions of Chrome, or if I'm somehow doing something wrong (for example, here is a page that has these settings: Missing elements when using selenium chrome driver to automatically 'Save as PDF').
I only included the default download location change in this code to verify it's accepting any changes at all - if you download one of the Python installs from that page, it will download to the new location and not to the standard download folder, so Chrome seems to be accepting these changes.
The problem appears to be the option "selectedDestinationID", which doesn't seem to do anything.
from selenium import webdriver
import time
import json
chrome_options = webdriver.ChromeOptions()
app_state = {
'recentDestinations': [{
'id': 'Save as PDF',
'origin': 'local'
}],
'selectedDestinationId': 'Save as PDF',
'version': 2
}
prefs = {
'printing.print_preview_sticky_settings.appState': json.dumps(app_state),
'download.default_directory': 'c:\\temp\\seleniumtesting\\'
}
chrome_options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path='C:\\temp\\seleniumtesting\\chromedriver.exe', options=chrome_options)
driver.get('https://www.python.org/downloads/release/python-373/')
time.sleep(25)
driver.close()
After the page launches, hitting ctrl+p brings up the printing page, but it defaults to the default printer. If I bring up the same page in my standard Chrome installation, it defaults to printing to PDF. I want to get to the point where I can add kiosk printing and then call window.print(), but as of now all that does is send it to the actual paper printer.
Thanks for any help anyone can offer. I'm stumped, and at this point it probably would have been faster to just save all of these manually.
It seems that if you have network printers configured they load up after opening the dialog and override your selectedDestination.
There is a preference "printing.default_destination_selection_rules" which seems to resolve.
prefs = {
"printing.print_preview_sticky_settings.appState": json.dumps(app_state),
"download.default_directory": "c:\\temp\\seleniumtesting\\".startswith(),
"printing.default_destination_selection_rules": {
"kind": "local",
"namePattern": "Save as PDF",
},
}
https://chromium.googlesource.com/chromium/src/+/master/chrome/common/pref_names.cc#1318
https://www.chromium.org/administrators/policy-list-3#DefaultPrinterSelection

Automate print/save web page as pdf in chrome - python 3.6

I am trying to create a script to automatically save read-only pdfs via Chrome's printing functionality to save it as another pdf in the same folder. This removes the 'read-only' feature. However while running the script I am not sure where I can specify my own specific destination folder and the script saves it in the Downloads folder directly.
Full props to https://stackoverflow.com/users/1432614/ross-smith-ii for the code below.
Any help will be very much appreciated.
import json
from selenium import webdriver
downloadPath = r'mypath\downloadPdf\\'
appState = {
"recentDestinations": [
{
"id": "Save as PDF",
"origin": "local"
}
],
"selectedDestinationId": "Save as PDF",
"version": 2
}
profile = {'printing.print_preview_sticky_settings.appState':json.dumps(appState)}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
chrome_options.add_argument('--kiosk-printing')
driver = webdriver.Chrome(chrome_options=chrome_options)
pdfPath = r'mypath\protected.pdf'
driver.get(pdfPath)
driver.execute_script('window.print();')
Ok, I think I figured out the solution. Just append the following line with the below code:
profile = {'printing.print_preview_sticky_settings.appState':json.dumps(appState),'savefile.default_directory':downloadPath}
It's not ideal still as you cannot specify the new file name you want but it works for now.
If anyone has a better solution, please do post it here. Thanks

Python Selenium: Unable to use proxy [duplicate]

I am using Firefox WebDriver in Python 2.7 with Selenium. My python program starts Firefox browser and visits different websites when I run the program. But, I need to set the proxy with authentication, so that when program visits any website, it will visit through the proxy server.
There are some similar questions on SO. But, there is no specific solution for Selenium Firefox WebDriver of Python.
Python Selenium Webdriver - Proxy Authentication
Running selenium behind a proxy server
Dup of: How to set proxy AUTHENTICATION username:password using Python/Selenium
Selenium-wire: https://github.com/wkeeling/selenium-wire
Install selenium-wire
pip install selenium-wire
Import it
from seleniumwire import webdriver
Auth to proxy
options = {
'proxy': {
'http': 'http://username:password#host:port',
'https': 'https://username:password#host:port',
'no_proxy': 'localhost,127.0.0.1,dev_server:8080'
}
}
driver = webdriver.Firefox(seleniumwire_options=options)
Warning
Take a look to the selenium-wire cache folder. I had a problem because it take all my disk space. You have to remove it sometimes in your script when you want.
In addition to running Firefox with a profile which has the credentials saved. You can do it loading an extension that writes in the loginTextbox and password1Textbox of chrome://global/content/commonDialog.xul (the alert window).
There are already some extensions that will do the job. For instance: Close Proxy Authentication
https://addons.mozilla.org/firefox/downloads/latest/close-proxy-authentication/addon-427702-latest.xpi
from selenium import webdriver
from base64 import b64encode
proxy = {'host': HOST, 'port': PORT, 'usr': USER, 'pwd': PASSWD}
fp = webdriver.FirefoxProfile()
fp.add_extension('closeproxy.xpi')
fp.set_preference('network.proxy.type', 1)
fp.set_preference('network.proxy.http', proxy['host'])
fp.set_preference('network.proxy.http_port', int(proxy['port']))
# ... ssl, socks, ftp ...
fp.set_preference('network.proxy.no_proxies_on', 'localhost, 127.0.0.1')
credentials = '{usr}:{pwd}'.format(**proxy)
credentials = b64encode(credentials.encode('ascii')).decode('utf-8')
fp.set_preference('extensions.closeproxyauth.authtoken', credentials)
driver = webdriver.Firefox(fp)
You can write own firefox extension for proxy, and launch from selenium. You need write 2 files and pack it.
background.js
var proxy_host = "YOUR_PROXY_HOST";
var proxy_port = YOUR_PROXY_PORT;
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: proxy_host,
port: proxy_port
},
bypassList: []
}
};
function proxyRequest(request_data) {
return {
type: "http",
host: proxy_host,
port: proxy_port
};
}
browser.proxy.settings.set({value: config, scope: "regular"}, function() {;});
function callbackFn(details) {
return {
authCredentials: {
username: "YOUR_USERNAME",
password: "YOUR_PASSWORD"
}
};
}
browser.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
browser.proxy.onRequest.addListener(proxyRequest, {urls: ["<all_urls>"]});
manifest.json
{
"name": "My Firefox Proxy",
"version": "1.0.0b",
"manifest_version": 2,
"permissions": [
"browsingData",
"proxy",
"storage",
"tabs",
"webRequest",
"webRequestBlocking",
"downloads",
"notifications",
"<all_urls>"
],
"background": {
"scripts": ["background.js"]
},
"browser_specific_settings": {
"gecko": {
"id": "myproxy#example.org"
}
}
}
Next you need packed this files to zip archive in DEFLATED mode with .xpi at end like my_proxy_extension.xpi.
You have two choices:
Sign your extension Firefox extension .xpi file structure: description, contents, creation, and installation
OR
Run unsigned. For this step:
Open firefox flags at about:config and set options xpinstall.signatures.required to false
OR
Update firefox profile in:
Windows: C:\Program Files\Mozilla Firefox\defaults\pref\channel-prefs.js
Linux: /etc/firefox/syspref.js
Add next line to end of file:
pref("xpinstall.signatures.required",false);
After this steps run selenium and install this extension:
from selenium import webdriver
driver = webdriver.Firefox()
driver.install_addon("path/to/my_proxy_extension.xpi")
driver.get("https://yoursite.com")
There is an example for Firefox + Python but without the authentication here. Then you can find other available parameters here in source code. So it looks like you need the following:
socksUsername
socksPassword
For example:
from selenium import webdriver
from selenium.webdriver.common.proxy import *
myProxy = "host:8080"
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy, # set this value as desired
'ftpProxy': myProxy, # set this value as desired
'sslProxy': myProxy, # set this value as desired
'noProxy': '' # set this value as desired
'socksUsername': = ''
'socksPassword': = ''
})
driver = webdriver.Firefox(proxy=proxy)
or with preferences:
driverPref = webdriver.FirefoxProfile()
driverPref.set_preference("network.proxy.type", 1)
.
.
.
driverPref.set_preference('network.proxy.socks', proxyHost)
driverPref.set_preference('network.proxy.socks_port', proxyPort)
driverPref.update_preferences()
driver = webdriver.Firefox(firefox_profile=driverPref)
EDIT:
I looked at it again and it seems that it is impossible to set authentication details in FF, even manually. The only way is just to remember the details that you have already entered which done by 2 parameters:
signon.autologin.proxy=true
network.websocket.enabled=false
that can be configured with the set_preference() method. You can also manually view all FF options by browsing to about:config.
In an addition to the answer with extension.
You can also use form filling to dynamically change credentials on your proxy. Just load the extension page, fill the form automatically and click save!
We can switch to authentication alert box and enter username password manually.
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference('network.proxy.ssl_port', int(ProxyPort))
profile.set_preference('network.proxy.ssl', ProxyHost)
profile.set_preference("network.proxy.http", ProxyHost)
profile.set_preference("network.proxy.http_port", int(ProxyPort))
webdriver = webdriver.Firefox(firefox_profile=profile, executable_path=GECKO_DRIVER_PATH)
webdriver.get("https://whatismyipaddress.com/")
try:
alert = webdriver.switch_to_alert()
print("switched to alert window")
alert.send_keys(proxy_username + Keys.TAB + proxy_password)
alert.accept()
webdriver.switch_to.default_content()
except Exception:
print("Error in alert switch")
pass

How to change proxy in selenium firefox webdriver while running? [duplicate]

Is there any way to dynamically change the proxy being used by Firefox when using selenium webdriver?
Currently I have proxy support using a proxy profile but is there a way to change the proxy when the browser is alive and running?
My current code:
proxy = Proxy({
'proxyType': 'MANUAL',
'httpProxy': proxy_ip,
'ftpProxy': proxy_ip,
'sslProxy': proxy_ip,
'noProxy': '' # set this value as desired
})
browser = webdriver.Firefox(proxy=proxy)
Thanks in advance.
This is a slightly old question.
But it is actually possible to change the proxies dynamically thru a "hacky way"
I am going to use Selenium JS with Firefox but you can follow thru in the language you want.
Step 1: Visiting "about:config"
driver.get("about:config");
Step 2 : Run script that changes proxy
var setupScript=`var prefs = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
prefs.setIntPref("network.proxy.type", 1);
prefs.setCharPref("network.proxy.http", "${proxyUsed.host}");
prefs.setIntPref("network.proxy.http_port", "${proxyUsed.port}");
prefs.setCharPref("network.proxy.ssl", "${proxyUsed.host}");
prefs.setIntPref("network.proxy.ssl_port", "${proxyUsed.port}");
prefs.setCharPref("network.proxy.ftp", "${proxyUsed.host}");
prefs.setIntPref("network.proxy.ftp_port", "${proxyUsed.port}");
`;
//running script below
driver.executeScript(setupScript);
//sleep for 1 sec
driver.sleep(1000);
Where use ${abcd} is where you put your variables, in the above example I am using ES6 which handles concatenation as shown, you can use other concatenation methods of your choice , depending on your language.
Step 3: : Visit your site
driver.get("http://whatismyip.com");
Explanation:the above code takes advantage of Firefox's API to change the preferences using JavaScript code.
As far as I know there are only two ways to change the proxy setting, one via a profile (which you are using) and the other using the capabilities of a driver when you instantiate it as per here. Sadly neither of these methods do what you want as they both happen before as you create your driver.
I have to ask, why is it you want to change your proxy settings? The only solution I can easily think of is to point firefox to a proxy that you can change at runtime. I am not sure but that might be possible with browsermob-proxy.
One possible solution is to close the webdriver instance and create it again after each operation by passing a new configuration in the browser profile
Have a try selenium-wire, It can even override header field
from seleniumwire import webdriver
options = {
'proxy': {
"http": "http://" + IP_PORT,
"https": "http://" + IP_PORT,
'custom_authorization':AUTH
},
'connection_keep_alive': True,
'connection_timeout': 30,
'verify_ssl': False
}
# Create a new instance of the Firefox driver
driver = webdriver.Firefox(seleniumwire_options=options)
driver.header_overrides = {
'Proxy-Authorization': AUTH
}
# Go to the Google home page
driver.get("http://whatismyip.com")
driver.close()

Categories