about tor selenium C# - c#

Hello guys I try to use tor in C# I find some sources on the website but I have some problems
please help me :
WebDriverWait Wait;
IWebDriver Driver;
String torBinaryPath = #"D:\Tor Browser\Browser\firefox.exe";
Process TorProcess = new Process();
TorProcess.StartInfo.FileName = torBinaryPath;
TorProcess.StartInfo.Arguments = "-n";
TorProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
TorProcess.Start();
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.proxy.type", 1);
profile.SetPreference("network.proxy.socks", "127.0.0.1");
profile.SetPreference("network.proxy.socks_port", 9150);
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
Driver = new FirefoxDriver(options);
Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(60));
Driver.Navigate().GoToUrl(#"http://whatismyipaddress.com/");
the problem is enter image description here

You need to use an option and not a profile.
Please check the example below.
FirefoxOptions opt = new FirefoxOptions();
opt.Profile = new FirefoxProfile();
opt.Profile.SetPreference("network.proxy.type", 1);
opt.Profile.SetPreference("network.proxy.socks", "127.0.0.1");
opt.Profile.SetPreference("network.proxy.socks_port", 9150);
this.Driver = new FirefoxDriver(opt);

Related

IDevTools instance does not contain CreateDevToolsSession method

I'm trying to intercept URLs containing a substring in C# using selenium chrome webdriver 4.0.0-beta4.
This is what I found and changed a little bit:
using V89 = OpenQA.Selenium.DevTools.V89;
using V89Net = OpenQA.Selenium.DevTools.V89.Network;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.DevTools;
ChromeOptions options = new ChromeOptions();
ChromeDriver webDriver;
IDevTools devTools;
public void InterceptRequestWithFetch(string url)
{
options.BinaryLocation = #"C:\Program Files\Google\Chrome Beta\Application\chrome.exe";
var service = ChromeDriverService.CreateDefaultService();
service.LogPath = AppDomain.CurrentDomain.BaseDirectory + "chromedriver.log";
service.EnableVerboseLogging = true;
webDriver = new ChromeDriver(service, options);
devTools = webDriver as IDevTools;
var devToolsSession = devTools.CreateDevToolsSession();
var fetch = devToolsSession.GetVersionSpecificDomains<V89.DevToolsSessionDomains>().Fetch;
var enableCommandSettings = new V89.Fetch.EnableCommandSettings();
var requestPattern = new V89.Fetch.RequestPattern();
requestPattern.RequestStage = V89.Fetch.RequestStage.Response;
requestPattern.ResourceType = V89Net.ResourceType.XHR;
requestPattern.UrlPattern = "*://*/*.jpg*";
enableCommandSettings.Patterns = new V89.Fetch.RequestPattern[] { requestPattern };
fetch.Enable(enableCommandSettings);
fetch.RequestPaused += RequestIntercepted;
webDriver.Navigate().GoToUrl(url);
}
void RequestIntercepted(object sender, V89.Fetch.RequestPausedEventArgs e)
{
richTextBox1.AppendText(e.Request.Url);
webDriver.Quit();
}
The problem is CreateDevToolsSession() does not exists and it seems like GetDevToolsSession() is the only option which does totally different job, but I tried it anyway and then my form froze, and codes past that line never executed.
I searched last three days for a solution but its just CreateDevToolsSession(). How can I use the DevTools if I won't be able to create a session?
This worked for me. Might not be exactly what you want, but it sets up devtools and can do whatever you normally would.
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.DevTools.V96.Network;
using DevToolsSessionDomains = OpenQA.Selenium.DevTools.V96.DevToolsSessionDomains;
public void DevtoolsExample()
{
IDevToolsSession session;
DevToolsSessionDomains devToolsSession;
//Setup WebDriver and devtools
driver = new ChromeDriver();
var baseUrl = ConfigurationHelper.Get<string>("TargetUrl");
//*this appears to create devtools session or get existing
IDevTools devTools = driver as IDevTools;
session = devTools.GetDevToolsSession();
devToolsSession = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
devToolsSession.Network.Enable(new EnableCommandSettings());
devToolsSession.Network.SetBlockedURLs(new SetBlockedURLsCommandSettings()
{
Urls = new string[] { "*://*/*.css", "*://*/*.jpg", "*://*/*.png" }
//Urls = new string[] { }
});
driver.Navigate().GoToUrl("https://someUrl.com");
}

Selenium WebDriver Factory picking same driver

I am making an WinForms application, using Visual Studio with Selenium webdriver. I am running some tests using different browser for each test, that are launch at the click of different winforms buttons.
I have created an Webdriver Factory class as follows:
class BrowserFactory
{
private static readonly IDictionary<string, IWebDriver> Drivers = new Dictionary<string, IWebDriver>();
private static IWebDriver driver;
public static IWebDriver Driver
{
get
{
if (driver == null)
throw new NullReferenceException("The WebDriver browser instance was not initialized. You should first call the method InitBrowser.");
return driver;
}
private set
{
driver = value;
}
}
public static void InitBrowser(string browserName)
{
switch (browserName)
{
case "Firefox":
if (driver == null)
{
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
options.BrowserExecutableLocation = $#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\Internet JS4\App\firefox64\firefox.exe";
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService($#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}");
driver = new FirefoxDriver(service, options);
Drivers.Add("Firefox", driver);
}
break;
case "Chrome":
if (driver == null)
{
var service = ChromeDriverService.CreateDefaultService($#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\ChromeDriver");
var options = new ChromeOptions();
service.HideCommandPromptWindow = true;
options.BinaryLocation = $#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\GoogleChromePortable\App\Chrome-bin\chrome.exe";
options.AddUserProfilePreference("disable-popup-blocking", "true");
driver = new ChromeDriver(service, options);
Drivers.Add("ChromeAscuns", driver);
}
break;
}
}
The code for first button:
BrowserFactory.InitBrowser("Firefox");
BrowserFactory.Driver.Navigate().GoToUrl("http://www.google.com");
The code for the second button:
BrowserFactory.InitBrowser("Chrome");
BrowserFactory.driver.Navigate().GoToUrl("http://www.bing.com");
When I click any of the buttons, it launches the correct webdriver (Firefox for first button and Chrome for the second). However, when I click the other button, it uses the same webdriver browser as the first occurence.
What am I missing in the code?
You appear to want to cache web drivers and reuse them. The problem is you are checking to see if a "driver" is already created, and if not create one, and cache that instance in a dictionary.
You need to consult the dictionary first before entering the switch statement and exit the method prematurely if a web driver by that name already exists. You also need to assume that when you fall in to the switch statement you will always be creating a new web driver.
public static void InitBrowser(string browserName)
{
if (Drivers.ContainsKey(browserName))
{
// Switch to existing web driver
driver = Drivers[browserName];
return;
}
// Initialize new web driver
switch (browserName)
{
case "Firefox":
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
options.BrowserExecutableLocation = $#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\Internet JS4\App\firefox64\firefox.exe";
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService($#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}");
driver = new FirefoxDriver(service, options);
Drivers.Add("Firefox", driver);
break;
case "Chrome":
var service = ChromeDriverService.CreateDefaultService($#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\ChromeDriver");
var options = new ChromeOptions();
service.HideCommandPromptWindow = true;
options.BinaryLocation = $#"{EcrisAdreseFrameW.Properties.Settings.Default["caleAppData"]}\GoogleChromePortable\App\Chrome-bin\chrome.exe";
options.AddUserProfilePreference("disable-popup-blocking", "true");
driver = new ChromeDriver(service, options);
Drivers.Add("ChromeAscuns", driver);
break;
}
}

ChromeDriver not logging

I am starting my selenium-driven headless chrome like this:
var options = new ChromeOptions();
options.AcceptInsecureCertificates = true;
options.AddArgument("--disable-gpu");
options.AddArgument("--no-sandbox");
options.AddArgument("--ignore-certificate-errors");
options.AddArgument("--disable-web-security");
options.AddArgument("--allow-insecure-localhost");
options.AddArgument("--allow-running-insecure-content");
options.AddArgument("--acceptInsecureCerts=true");
options.AddArgument("--proxy-server='direct://'");
options.AddArgument("--proxy-bypass-list=*");
options.AddArgument("--disable-extensions");
options.AddArgument("--disable-infobars");
options.AddArgument("--window-size=1920,1080");
options.AddArgument("--incognito");
options.AddArgument("--headless");
options.AddArgument("--log-level=ALL");
options.AddArgument("log-path=c:\\chromedriver.log");
options.SetLoggingPreference(OpenQA.Selenium.LogType.Driver, OpenQA.Selenium.LogLevel.All);
var svc = ChromeDriverService.CreateDefaultService();
svc.Port = RandomHelper.Randomiser.Next(29700, 29900);
Context.Driver = new ChromeDriver(svc, options, TimeSpan.FromMinutes(2));
However, after running (and seeing successful test output - failing and passing tests) I see no file at c:\chromedriver.log.
What am I doing wrong?
Really frustrating developing with Selenium, but found how to log with ChromeDriver:
var options = new ChromeOptions();
options.AcceptInsecureCertificates = true;
options.AddArgument("--disable-gpu");
options.AddArgument("--no-sandbox");
options.AddArgument("--ignore-certificate-errors");
options.AddArgument("--disable-web-security");
options.AddArgument("--allow-insecure-localhost");
options.AddArgument("--allow-running-insecure-content");
options.AddArgument("--acceptInsecureCerts=true");
options.AddArgument("--proxy-server='direct://'");
options.AddArgument("--proxy-bypass-list=*");
options.AddArgument("--disable-extensions");
options.AddArgument("--disable-infobars");
options.AddArgument("--window-size=1920,1080");
options.AddArgument("--incognito");
options.AddArgument("--headless");
options.AddArgument("--log-level=ALL");
options.AddArgument("log-path=c:\\chromedriver.log");
options.SetLoggingPreference(OpenQA.Selenium.LogType.Driver, OpenQA.Selenium.LogLevel.All);
var svc = ChromeDriverService.CreateDefaultService();
svc.Port = RandomHelper.Randomiser.Next(29700, 29900);
svc.LogPath = #"c:\chromedriver.log";
svc.EnableVerboseLogging = true;
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
options.SetLoggingPreference(LogType.Client, LogLevel.All);
options.SetLoggingPreference(LogType.Driver, LogLevel.All);
options.SetLoggingPreference(LogType.Profiler, LogLevel.All);
options.SetLoggingPreference(LogType.Server, LogLevel.All);
Context.Driver = new ChromeDriver(svc, options, TimeSpan.FromMinutes(2));

PhantomJS C# how to change Default language

Trying to set a Default language in my program. But after much googling i dident find any answers.
How can i input standard english accept language?
is there any document i can read for all functions i can use in c# with PhantomJS? I dident find anything more then playing in Visualstudio controlls.
var driverService = PhantomJSDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
driverService.LoadImages = false;
driverService.SslProtocol = "tlsv1";
driverService.IgnoreSslErrors = true;
driverService.ProxyType = "http";
driverService.Proxy = "";
using (var driver = new PhantomJSDriver(driverService))
{
driver.Manage().Window.Size = new Size(1920, 1080); // Size is a type in assembly "System.Drawing"
driver.Manage().Cookies.DeleteAllCookies();
driver.Url = "https://www.thewebsite.com";
Thread.Sleep(5000); // 5sec
try
{
driver.FindElement(By.Name("email")).SendKeys("MyEmail");
driver.FindElement(By.Name("fullName")).SendKeys("MyName");
driver.FindElement(By.Name("username")).SendKeys("MyUsername");
driver.FindElement(By.Name("password")).SendKeys("MyPassword");
driver.TakeScreenshot().SaveAsFile("LetsSnapascreenshot.png", ImageFormat.Png);
}
catch (OpenQA.Selenium.NoSuchElementException exception)
{
var exmsg = exception;
driver.TakeScreenshot().SaveAsFile("Snaperrorscreenshot.png", ImageFormat.Png);
}
}
I found the solution for this if anyone else is looking for it.
PhantomJSOptions options = new PhantomJSOptions();
options.AddAdditionalCapability("phantomjs.page.customHeaders.Accept-Language", "en,en;q=0.5");
IWebDriver driver = new PhantomJSDriver(options);
And now it outputs the accept-Language correct
you can try to add a header
PhantomJSOptions options = new PhantomJSOptions();
options.AddAdditionalCapability("Accept-Language","en-DE,en;q=0.5");
IWebDriver driver = new PhantomJSDriver(options);
or write in your index.html as described in this answer
<script>
localStorage.lang = 'en';
</script>

Run Selenium grid 2 with custom firefox profile

How to run Selenium grid 2 with custom firefox profile from code.
Here is code I'm having now:
DesiredCapabilities capabilities = DesiredCapabilities.Firefox();
capabilities.SetCapability(CapabilityType.AcceptSslCertificates, true);
capabilities.SetCapability(CapabilityType.HasNativeEvents, false);
capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
capabilities.IsJavaScriptEnabled = true;
Uri url = new Uri("http://localhost:4444/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url, capabilities);
return driver;
The only thing I left is to force Selenium grid use my custom profile.
Found solution:
var firefoxProfile = new FirefoxProfile();
// configure firefoxProfile ...
DesiredCapabilities capabilities = DesiredCapabilities.Firefox();
capabilities.SetCapability(CapabilityType.AcceptSslCertificates, true);
capabilities.SetCapability(CapabilityType.HasNativeEvents, false);
capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
capabilities.IsJavaScriptEnabled = true;
capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, firefoxProfile.ToBase64String());
Uri url = new Uri("http://localhost:4444/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url, capabilities);
return driver;

Categories