Change PhantomJS proxy settings while running - c#

I'm using Selenium and PhantomJs in a C#/Winforms application.
I have to set the proxy for PhantomJS before running it with this code:
var driverService = PhantomJSDriverService.CreateDefaultService("phantomjsdriver");
Proxy proxy = new Proxy();
proxy.HttpProxy = string.Format("xx.xx.xx.xx:port");
driverService.ProxyType = "http";
driverService.Proxy = proxy.HttpProxy;
driverService.AddArgument(string.Format("--proxy-auth={0}:{1}", "username", "password"));
using (var driver = new PhantomJSDriver(driverService))
{
//......
}
Now I have a list of proxies! And I need to change the proxy after each request, So what I do now is just quitting the driver then run it again with a new proxy.
It's not a very efficient way so I was wondering if there was any method to change the proxy without quitting the driver!
Thanks in advance!
EDIT
So there is a function in PhantomJS that enable us to change the proxy at any time.
Any idea how to use it under Selenium?

I found the solution, After finding that PhantomJS has a setProxy function, It was just a matter of how to use it:
String script = "return phantom.setProxy(\"{0}\", {1}, \"http\", \"{2}\", \"{3}\")";
string func = string.Format(script, ppp.IP, ppp.Port, ppp.Username, ppp.Password);
Object obj = driver.ExecutePhantomJS(func);
Hope this code helps someone else!

Related

How to launch a specific URL with Firefox in C#

I'm trying to launch a specific URL using Firefox. But I'm only able to open Firefox browser and not able to launch that URL.
class BrowserHelper
{
IWebDriver driver;
string path = Path.Combine(Environment.CurrentDirectory, #"gecko\\");
public void Navigate(string url)
{
path = path.Replace(#"\", #"\\");
var driverService = FirefoxDriverService.CreateDefaultService(path);
driverService.HideCommandPromptWindow = true;
if (driver == null)
{
driver = new FirefoxDriver(driverService);
}
driver.Url = url;
driver.Navigate().GoToUrl(driver.Url);
driver.Manage().Window.Maximize();
}
}
class Realtest
{
BrowserHelper BH = new BrowserHelper();
public void test()
{
string search ="apple";
BH.Navigate("https://www.google.com/search?q=" + search);
}
}
And I can only get this page:
Here's the final URL I want to launch: https://www.google.com.sg/search?q=apple
Any suggestions? Thanks in advance.
I have tried the below code (in Java), and it's working fine by launching the browser and loading the URL also.
System.setProperty("webdriver.gecko.driver","Drivers/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com.sg/search?q=apple");
So I feel the problem is with geckodriver version and FireFox browser installed in your local machine. I would suggest you update FireFox and geckodriver to the latest version.
There is also a pretty easy solution using the command line with c#.
Simply execute the following command to open a new Firefox Tab with the given URL:
start firefox wikipedia.de
You can also start a new Firefox instance if you wish:
start firefox -new-instance wikipedia.de
Last but not least the .Net Code to execute the commands in CLI:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
Arguments = "/c start firefox wikipedia.de",
CreateNoWindow = true,
FileName = "CMD.exe"
});
There is also a lot of other stuff that can be done with Firefox commandLine paramters. You an find all of them here:
https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options?redirectlocale=en-US&redirectslug=Command_Line_Options
This also works with chrome and opera, simply call
start opera wikipedia.de
instead of firefox.
You do not need to set driver.Url, remove that line.
driver.Navigate().GoToUrl(url);
driver.Manage().Window.Maximize();
Also, if you simply want to launch a single URL without interacting with the page, then Selenium is overkill.

Selenium Why setting acceptuntrustedcertificates to true for firefox driver doesn't work?

I'm developping some selenium tests and I face an important issue because I didn't found a "real" solution when I test my site with secure connection (HTTPS). All solutions I found on stackoverflow are out of date or doesn't work:
I am writing a Selenium script in Firefox but I am getting "Untrusted Certificate"
How to disable Firefox's untrusted connection warning using Selenium?
Handling UntrustedSSLcertificates using WebDriver
The only workaround I have is to use the nightly mozilla release as indicated on github: https://github.com/mozilla/geckodriver/issues/420
private IWebDriver driver;
private string baseURL;
private FirefoxOptions ffOptions;
private IWait<IWebDriver> wait;
[SetUp]
public void SetupTest()
{
ffOptions = new FirefoxOptions();
ffOptions.BrowserExecutableLocation = #"D:\AppData\Local\Nightly\firefox.exe";
FirefoxProfile profile = new FirefoxProfile();
profile.AssumeUntrustedCertificateIssuer = false;
profile.AcceptUntrustedCertificates = true;
ffOptions.Profile = profile;
ffOptions.LogLevel = FirefoxDriverLogLevel.Info;
driver = new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), ffOptions, TimeSpan.FromSeconds(30));
//[...]
}
Configuration:
Firefox v47.0.1, v49.0.2, v51.0.1, v52.0b9 (i tried these differents versions)
geckodriver 0.14
selenium 3.1.0
Does anyone have a solution to avoid using nightly release ?
For information I have access only to stackoverflow and github due to my internet policy, and please don't suggest me to use chrome!
Thank for your help!
Yeah, it's a bug on the geckodriver. You can find it here!
Setting the AcceptInsecureCertificates property to true in the FirefoxOptions fixed this problem for me. Here's what my initialization looked like after this change:
var profile = new FirefoxProfile();
profile.DeleteAfterUse = true;
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris", LocalURL);
profile.SetPreference("network.automatic-ntlm-auth.allow-non-fqdn", true);
profile.SetPreference("webdriver_accept_untrusted_certs", true);
// Only setting this property to true did not work for me either
profile.AcceptUntrustedCertificates = true;
profile.AssumeUntrustedCertificateIssuer = false;
return new FirefoxDriver(new FirefoxOptions
{
Profile = profile,
// When I also added this line, it DID work
AcceptInsecureCertificates = true
});

C# implementation of RemoteWebDriver fails to install Chrome extension

This ticket is related to ticket 1578 for Selenium , but my issue is with Chrome and not Firefox as in that ticket.
Installing and configuring an extension works when using a local driver. Doing the same using the C# implementation of RemoteWebDriver does not. Tested this with Chrome.
In my test case, the remote execution was done against SauceLabs. Contacted their support and they verified that installing extensions via RemoteWebDriver works in the JAVA implementation, but fails using the C# implementation.
To quote from their support ticket:
"I tried this myself and I was running into issues on my own end, so this may be a flaw with the C# Selenium bindings with RemoteWebDriver."
My code:
private IWebDriver GetSauceLabsDriver(){
var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
ChromeOptions options = new ChromeOptions();
options.AddExtensions(outPutDirectory + #"\3.1.3_0.crx");
//DesiredCapabilities caps = (DesiredCapabilities)options.ToCapabilities();
var caps = new DesiredCapabilities();
caps.SetCapability(ChromeOptions.Capability, options.Extensions[0]);
caps.SetCapability(CapabilityType.BrowserName, "chrome");
caps.SetCapability(CapabilityType.Version, "53.0");
caps.SetCapability(CapabilityType.Platform, "Windows 10");
caps.SetCapability("deviceName", "");
caps.SetCapability("deviceOrientation", "");
caps.SetCapability("username", "kin");
caps.SetCapability("accessKey", "9cd6-438e-a9635b70953d");
caps.SetCapability("name", TestContext.CurrentContext.Test.Name);
return new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), caps,
TimeSpan.FromSeconds(600));
}
This is a common mistake made by users of the .NET bindings. You should almost never be using the DesiredCapabilities class directly in your code. Rather, you should almost exclusively be using the ChromeOptions class to set all of the options before instantiaung the driver, and use the .ToCapabilitied() method to convert it to an ICapabilities object that can be used with the RemoteWebDriver constructor. In your specific case, that would look like this:
private IWebDriver GetSauceLabsDriver()
{
var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
ChromeOptions options = new ChromeOptions();
options.AddExtensions(outPutDirectory + #"\3.1.3_0.
// Add capabilities that belong at the top
// level of the capabilities object as opposed
// to part of the chromeOptions capability. Note
// that setting the browser name is entirely
// redundant and thus is not done. Likewise,
// deviceName and deviceOrientation are
options.AddAdditionalCapability(CapabilityType.Version, "53.0", true);
options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
options.AddAdditionalCapability("username", "kin", true);
options.AddAdditionalCapability("accessKey", "9cd6-438e-a9635b70953d", true);
options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);
return new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), options.ToCapabilities(),
TimeSpan.FromSeconds(600));
}

How to start IE in private mode in c# with selenium webdriver

I'm starting using selenium Webdriver with c# and Visualstudio.
I would like to start Internetexplorer in private mode. So I have not to care about old browsing data during my test.
I searched for quite a long time now to find how to do this.
Sadly I could not find a solution.
Could anybody provide me with a working code snippet showing how to start IE in private mode from c# code?
I used the following command to start the browser normally:
Context.Instance.Driver = new InternetExplorerDriver();
I tried to add this to make it work:
InternetExplorerOptions options = new InternetExplorerOptions();
options.BrowserCommandLineArguments = "--private";
Context.Instance.Driver = new InternetExplorerDriver(options);
This was niether a success.
Finally, I tried this also:
InternetExplorerDriverService service = InternetExplorerDriverService.CreateDefaultService();
service.SuppressInitialDiagnosticInformation = true;
InternetExplorerOptions options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
options.BrowserCommandLineArguments = "-private";
Context.Instance.Driver = new InternetExplorerDriver(service, options);
I would like to have IE running in private mode for my tests.
Here, InternetExplorerOptions Members page; it is stated that BrowserCommandLineArguments property only has an effect when the ForceCreateProcessApi is true. ForceCreateProcessApi default value is false.
Would you please try to set it manually?
options.ForceCreateProcessApi = true;
options.BrowserCommandLineArguments = "-private";

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

Is there any way to maximize the browser window using WebDriver (Selenium 2) with C#?
driver.Manage().Window.Maximize();
This works for IE and Firefox. Chrome does not work. There is a bug submitted for this on ChromeDriver project.
Meanwhile, the get around for the chrome is to implement what Joey V. and Coder323 suggested.
ChromeOptions options = new ChromeOptions();
options.addArgument("--start-maximized");
driver = new ChromeDriver(options);
Java
driver.manage().window().maximize();
Python
driver.maximize_window()
Ruby
#driver.manage.window.maximize
OR
max_width, max_height = driver.execute_script("return [window.screen.availWidth, window.screen.availHeight];")
#driver.manage.window.resize_to(max_width, max_height)
OR
target_size = Selenium::WebDriver::Dimension.new(1600, 1268)
#driver.manage.window.size = target_size
For IE and Firefox:
driver.manage().window().maximize();
For Chrome:
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver( options )
There's an outstanding issue to add this functionality to WebDriver, which can be tracked here: http://code.google.com/p/selenium/issues/detail?id=174
A workaround would be to use the JavascriptExector as follows:
public void resizeTest() {
driver.Navigate().GoToUrl("http://www.example.com/");
((IJavaScriptExecutor)driver).ExecuteScript("window.resizeTo(1024, 768);");
}
Test step/scenario:
1. Open a browser and navigate to TestURL
2. Maximize the browser
Maximize the browser with C# (.NET):
driver.Manage().Window.Maximize();
Maximize the browser with Java :
driver.manage().window().maximize();
Another way to do with Java:
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenResolution = new Dimension((int)
toolkit.getScreenSize().getWidth(), (int)
toolkit.getScreenSize().getHeight());
driver.manage().window().setSize(screenResolution);
You can use something like this (C#):
driver.Manage().Window.Size = new Size(1024, 768);
If you are using the Chrome Driver you can set the capabilities
var capabilities = new DesiredCapabilities();
var switches = new List<string>
{
"--start-maximized"
};
capabilities.SetCapability("chrome.switches", switches);
new ChromeDriver(chromedriver_path, capabilities);
Simply use Window.Maximize() command
WebDriver driver= new ChromeDriver()
driver.Manage().Window.Maximize();
For Java:
driver.manage().window().maximize();
It will work in IE, Mozilla, Chrome
The following Selenium Java code snippet worked for me:
driver.manage().window().setPosition(new Point(0,0));
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Dimension dim = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setSize(dim);
I had the same problem, but the problem can be solved by using following code.
driver.manage().window().fullscreen();
For C#:
driver.Manage().Window.Maximize();
For Java:
driver.manage().window().maximize();
We have observed bug with new driver libraries. You can use slightly old jars which are able to handle new browsers versions.
The main generic option is :-
driver.manage().window().maximize();
You can also use other option for maximizing the browser window.
Example:-
Add below option and pass it to driver:-
chromeOptions.addArguments("--start-maximized");
The full code will look like below :-
System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
driver = new ChromeDriver(chromeOptions);
OR
Toolkit toolkit = Toolkit.getDefaultToolkit();
int Width = (int) toolkit.getScreenSize().getWidth();
int Height = (int)toolkit.getScreenSize().getHeight();
//For Dimension class, Import following library "org.openqa.selenium.Dimension"
driver.manage().window().setSize(new Dimension(Width,Height));
driver.get("https://google.com");
Try this on safari :-
JavascriptExecutor jse = (JavascriptExecutor)driver;
String screenWidth = jse.executeScript("return screen.availWidth").toString();
String screenHeight = jse.executeScript("return screen.availHeight").toString();
int intScreenWidth = Integer.parseInt(screenWidth);
int intScreenHeight = Integer.parseInt(screenHeight);
Dimension d = new Dimension(intScreenWidth, intScreenHeight);
driver.manage.window.setSize(d);
using System.Windows.Forms;
using System.Drawing;
public static void MaximizeBrowser(this IE myBrowser)
{
myBrowser.SizeWindow(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
}
I used Jim's code, but slightly modified for use with WatiN and C# to maximize the browser.
You can use Selenium Emulation in WebDriver:
selenium = new WebDriverBackedSelenium(driver,url);
selenium.windowMaximize();
I used this solution
OpenQA.Selenium.Chrome.ChromeOptions chromeoptions = new OpenQA.Selenium.Chrome.ChromeOptions();
chromeoptions.AddArgument("--start-maximized");
OpenQA.Selenium.Chrome.ChromeDriver chrome = new OpenQA.Selenium.Chrome.ChromeDriver(chromeoptions);
For Chrome
ChromeOptions options = new ChromeOptions();
IWebDriver driver = new ChromeDriver(options);
driver.Manage().Window.Maximize();
There is a function that you can use to maximize the window in Python which is window_maximize(). And this is how I'm using it.Hope this helps -
from selenium import selenium
sel = selenium('localhost', 4444, '*firefox', 'http://10.77.21.67/')
sel.start()
sel.open('/')
sel.wait_for_page_to_load(60000)
#sel.window_focus()
sel.window_maximize()
png = sel.capture_screenshot_to_string()
f = open('screenshot.png', 'wb')
f.write(png.decode('base64'))
f.close()
sel.stop()
C# client drivers:
driver = new FirefoxDriver(firefoxProfile);
driver.Manage().Window.Size = new System.Drawing.Size(System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width+10, System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height+10);
===> also add a reference to the .NET assembly "System.Windows.Forms"
... the only problem is that it's not positioned correctly
... please comment if you can correct this
Here's what worked for me in C#, firefoxDriver is global to the class:
in the usings:
using System.Drawing;
using System.Windows.Forms;
in the code:
this.firefoxDriver = new FirefoxDriver();
this.firefoxDriver.Manage().Window.Position = new Point(0, 0);
this.firefoxDriver.Manage().Window.Size = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
For Webdriverjs (node.js), the following maximizes chrome window.
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).build();
driver.manage().window().maximize();
driver.get('hxxp://localhost:8888');
This option is fine for me :
ChromeOptions options = new ChromeOptions();
options.addArguments("start-fullscreen");
This option works on all OS.
The below line of code would maximize IE, Chrome and Mozilla
driver.manage().window().maximize();
The above line of code and other workarounds mentioned in the post did not work for NodeWebKit browser, so as a workaround i had to use native C# code as mentioned below:
public static void MaximiseNWKBrowser(IWebDriver d)
{
var body = UICommon.GetElement(By.TagName("body"), d);
body.Click();
string alt = "%";
string space = " ";
string down = "{DOWN}";
string enter = "{ENTER}";
SendKeys.SendWait(alt + space);
for(var i = 1; i <= 6; i++)
{
SendKeys.SendWait(down);
}
SendKeys.SendWait(enter);
}
So this workaround basically uses "ALT+SPACE" to bring up the browser action menu to select "MAXIMIZE" from the options and presses "ENTER"
Through the below code i'm able to maximize the window,
((JavascriptExecutor) driver).executeScript("if(window.screen){
window.moveTo(0, 0);
window.resizeTo(window.screen.availWidth, window.screen.availHeight);
};");
This is working fine for me.
Capybara.current_session.driver.browser.manage.window.resize_to(1800, 1000)
I tried many of the answers above, but none work well.
My chrome driver version is 2.7 and Iam using selenium-java vesion is 2.9.0.
The official document suggests using:
var capabilities = new DesiredCapabilities();
var switches = new List<string>
{
"--start-maximized"
};
capabilities.SetCapability("chrome.switches", switches);
new ChromeDriver(chromedriver_path, capabilities);
The above also does not work. I checked the chrome driver JsonWireProtocol:
http://code.google.com/p/selenium/wiki/JsonWireProtocol
The chrome diver protocol provides a method to maximize the window:
/session/:sessionId/window/:windowHandle/maximize,
but this command is not used in selenium-java. This means you also send the command to chrome yourself. Once I did this it works.
Chrome driver already support:
Java:
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
For me, none of the solutions above worked when working with Selenium Web Driver C# + Chrome:
window.resizeTo(1024, 768); - I want to use the whole screen
--start-maximized - it is ignored
driver.manage().window().maximize(); - does not work because it requires some extension and I am not allowed to use Chrome extensions
I managed to get it working using InputSimulator:
var inputSim = new InputSimulator();
// WinKey + UP = Maximize focused window
inputSim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.UP);
You can try with this code to maximize chrome window.
ChromeOptions options = new ChromeOptions();
options.addArguments("--window-size=1920,1080");
WebDriver driver = new ChromeDriver(options);

Categories

Resources