AsValeO
AsValeO

Reputation: 3039

Change Proxy at runtime in Selenium.Webdriver + PhantomJS using C#

There is a way to dinamically change proxy in PhantomJS at runtime. Here's the python code:

driver = webdriver.PhantomJS()
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')
driver.execute('executePhantomScript', {'script': '''phantom.setProxy("10.0.0.1", 80);''', 'args' : [] })

In C# I'm trying:

((IJavaScriptExecutor)driver).ExecuteScript(@"phantom.setProxy(""10.0.0.1"", 80)");

Getting exception:

{"errorMessage":"Can't find variable: phantom","request":{"headers":{"Accept":"application/json, image/png","Connection":"Close","Content-Length":"62","Content-Type":"application/json;charset=utf-8","Host":"localhost:57378"},"httpVersion":"1.1","method":"POST","post":"{\"script\":\"phantom.setProxy(\\"10.0.0.1\\", 80)\",\"args\":[]}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/513f2130-26b4-11e7-b459-45c0e08b428c/execute"}}

Upvotes: 0

Views: 841

Answers (1)

JimEvans
JimEvans

Reputation: 27486

One limitation in .NET is that you won't be able to do this remotely (via Selenium Grid or similar); you would only be able to do this locally. The code to do so would look something like the following:

// WARNING! Untested code written without benefit of
// an IDE. Might not run or even compile without modification.
// First, cast the IWebDriver interface back to the concrete
// PhantomJSDriver implementation.
PhantomJSDriver phantomDriver = driver as PhantomJSDriver;
if (phantomDriver != null)
{
    // If the cast succeeded, the implementation has the
    // ExecutePhantomJS method, which executes script in
    // the browser context instead of the page context.
    phantomDriver.ExecutePhantomJS("phantom.setProxy('10.0.0.1', 80);");
}

Upvotes: 1

Related Questions