addScriptToEvaluateOnNewDocument Selenium (Does not work) - c#

I need to execute addScriptToEvaluateOnNewDocument method of Google Headless Chrome in C# .Net. I basically need to execute Javascript before any other javascript is executed on the documents. Here is my code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
namespace User
{
class Program
{
//public static IWebDriver driver = new ChromeDriver();
public static IWebDriver driver;
public static double magnification = 2;
static void Main(string[] args)
{
ChromeOptions options = new ChromeOptions();
//options.AddArgument("Page.addScriptToEvaluateOnNewDocument");
options.AddArgument("--window-size=1920,1080");
options.AddUserProfilePreference("Page.addScriptToEvaluateOnNewDocument", "alert('INJECTED SCRIPT')");
driver = new ChromeDriver(options);
var action = new OpenQA.Selenium.Interactions.Actions(driver);
System.Threading.Thread.Sleep(1000);
driver.Navigate().GoToUrl("https://google.com");
System.Threading.Thread.Sleep(10000);
}
}
}
But the alert isn't fired (i have tried other JavaScript code besides alert - nothing seems to work)

Try this.After initialize the driver.Hope this will work.
driver.ExecuteJavaScript("alert(0);")
OR
driver.Scripts().ExecuteScript("alert(0);")

I have only done this in Python but it should work the same way.
The chromedriver should expose a function named execute_cdp_cmd()
You can use this to run JavaScript before the page JavaScript is run. See the python example below. Note that you should add the code shown below after creating the driver but before you get the web page.
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
alert(0);
"""
})
I don't have a C# example, but this might help.

using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.DevTools.V91.Page;
using OpenQA.Selenium.Support.UI;
using RandomNameGeneratorLibrary;
using Network = OpenQA.Selenium.DevTools.V91.Network;
using DevToolsSessionDomains = OpenQA.Selenium.DevTools.V91.DevToolsSessionDomains;
IDevTools devTools = driver as IDevTools;
session = devTools.GetDevToolsSession();
var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
domains.Page.AddScriptToEvaluateOnNewDocument(new AddScriptToEvaluateOnNewDocumentCommandSettings()
{
Source = jscode,
});

Related

How to Find the reCAPTCHA element and click on it in c# Selenium

Hello everyone I need some help. There is URL: http://lisans.epdk.org.tr/epvys-web/faces/pages/lisans/petrolBayilik/petrolBayilikOzetSorgula.xhtml. As you can see in screenshot I need to click checkbox Captcha.
https://i.stack.imgur.com/xjXaA.png
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace AkaryakitSelenium
{
class Program
{
private static string AkaryakitLink = "http://lisans.epdk.org.tr/epvys-web/faces/pages/lisans/petrolBayilik/petrolBayilikOzetSorgula.xhtml";
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
driver.Navigate().GoToUrl(AkaryakitLink);
var kategoriCol = driver.FindElements(By.CssSelector(".ui-selectonemenu-trigger.ui-state-default.ui-corner-right"));
var x = kategoriCol[3];
x.Click();
var deneme = driver.FindElement(By.Id("petrolBayilikOzetSorguKriterleriForm:j_idt52_1"));
deneme.Click();
var check = driver.FindElement(By.Id("recaptcha-anchor"));
check.Click();
}
}
}
And lastly this error that I am facing:
"OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to
locate element: {"method":"css
selector","selector":"#recaptcha-anchor"}"
Thank you for your help.
The element you are looking for is inside an iframe :
//iframe[#title='reCAPTCHA']
first you need to switch to iframe like this :
new WebDriverWait(driver, TimeSpan.FromSeconds(3)).Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.XPath("//iframe[#title='reCAPTCHA']")));
then you can perform a click on it :
var check = driver.FindElement(By.Id("recaptcha-anchor"));
check.Click();
PS : captchas are not meant to be automated. since Captcha stands for CAPTCHA stands for the Completely Automated Public Turing test to tell Computers and Humans Apart.
You can not bypass captcha with Selenium.
It is designed to avoid automated access to web pages as described here and in many other places.

How can I integrate selenium tests with sauce labs in c#?

On saucelabs website they provide a code snippet like this:
WebDriver webDriver = new WebDriver();
webDriver.set(new RemoteWebDriver(
new URL("https://UrlHEREagwgwgqwg4894+4+91gwgq")
))
When I add this to my tests, under WebDriver it says type or namespace 'WebDriver' could not be found. It is coming up for a namespace. For my Selenium tests I am using IWebDriver. I tried to change the WebDriver to IWebDriver and that didn't work. I also get the same error under the URL saying the namespace could not be found. For that one it does show for a namespace using System.Security.Policy; If I add that then I get an error under
new URL("https://UrlHEREagwgwgqwg4894+4+91gwgq")
Argument 1: cannot convert from 'System.Security.Policy.Url' to 'OpenQA.Selenium.DriverOptions'
This is how I am trying to use it. I was using ChromeDriver for my selenium tests but commented that part out to test on other browsers with saucelabs. This is my first time working with selenium/saucelabs so what I am doing my be completely off and I appreciate any advice.
[Fact]
public static void ClickDownloadButton()
{
WebDriver driver = new WebDriver();
driver.set(new RemoteWebDriver(
new Url("https://UrlHEREagwgwgqwg4894+4+91gwgq")
));
//using IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl(BaseUrl.downloadsUrl);
var login = new Login(driver);
login.EnterEmail();
login.EnterPassword();
login.HitSubmit();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
var downloadButton = wait.Until((d) => d.FindElements(By.LinkText("Download File")));
foreach (var button in downloadButton)
{
IWebElement element = wait.Until((d) => d.FindElement(By.LinkText("Download File")));
element.Click();
}
driver.Quit();
}
Here are the using statements:
using Xunit;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Security.Policy;
using OpenQA.Selenium.Remote;
Check out our demo C# repository with tons of examples.
Here's a working example that you can use from the following file:
using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
namespace Selenium3.Nunit.Scripts.SimpleExamples
{
[TestFixture]
[Category("SimpleTest")]
public class SimpleSauceTest
{
IWebDriver _driver;
[Test]
public void SimpleTest()
{
//TODO please supply your Sauce Labs user name in an environment variable
var sauceUserName = Environment.GetEnvironmentVariable(
"SAUCE_USERNAME", EnvironmentVariableTarget.User);
//TODO please supply your own Sauce Labs access Key in an environment variable
var sauceAccessKey = Environment.GetEnvironmentVariable(
"SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability(CapabilityType.Version, "latest", true);
options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
options.AddAdditionalCapability("username", sauceUserName, true);
options.AddAdditionalCapability("accessKey", sauceAccessKey, true);
options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);
options.AddAdditionalCapability("build", "ShwabTeamName:" + DateTime.Now, true);
_driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"), options.ToCapabilities(),
TimeSpan.FromSeconds(600));
_driver.Navigate().GoToUrl("https://www.google.com");
Assert.Pass();
}
[TearDown]
public void CleanUpAfterEveryTestMethod()
{
var passed = TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed;
((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
}
}
Don't forget to install the correct Nuget packages so you have the corresponding resources. This is the minimum that you'll need:
<package id="Selenium.Support" />
<package id="Selenium.WebDriver" />
Side Note:
Don't use static methods as it'll make it impossible for you to parallelize.

C# Selenium bot element selection trouble

I am trying to make a bot that goes through drop-downs and makes selections but it's having trouble finding the element. The code is below.
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.Extensions;
using OpenQA.Selenium.Support.UI;
namespace selenium_test
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver;
driver = new ChromeDriver("C:\\");
Console.WriteLine("ChromeDriver Initialized");
driver.Url = "https://odyssey.gwinnettcourts.com/Portal/Home/Dashboard/26";
IWebElement typeElement = driver.FindElement(By.XPath(".//option[#id='cboHSSearchBy']"));
var typeSelect = new SelectElement(typeElement);
typeSelect.SelectByValue("JudicialOfficer");
typeElement.Click();
}
}
}
what exactly is the error? I can only assume that it is taking time to find element.
add wait time maybe? also, why using xpath when you have id of controls? id is quicker!
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists((By.Id("cboHSSearchBy"))));

Getting an Exception System.ComponentModel.Win32Exception : The system cannot find the file specified in Sikuli C#

I am getting an exception System.ComponentModel.Win32Exception : The system cannot find the file specified when i employ Sikuli in C# using selenium.
I have referred to other posts in Stack but i have not not got a solution for that.
I am also running VS 2017 in administrator mode
I have latest copy of Rest-Api Jar in /Debug folder.
Below is my code
using System;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using Sikuli4Net.sikuli_REST;
using Sikuli4Net.sikuli_UTIL;
using SikuliModule;
namespace DownloadFile
{
public class Download
{
private IWebDriver driver;
private APILauncher launcher;
[SetUp]
public void setup()
{
driver = new FirefoxDriver();
launcher = new APILauncher(true);
driver.Navigate().GoToUrl("https://java.com/en/download/");
driver.Manage().Window.Maximize();
}
[Test]
public void TestMethod1()
{
new WebDriverWait(driver, TimeSpan.FromSeconds(60)).Until(ExpectedConditions.ElementExists((By.XPath("//span[contains(text(),'Free Java Download')]")))).Click();
new WebDriverWait(driver, TimeSpan.FromSeconds(60)).Until(ExpectedConditions.ElementExists((By.XPath("//span[contains(text(),'Agree and Start Free Download')]")))).Click();
launcher.Start();
Screen screen = new Screen();
Pattern Click_Save = new Pattern("C:/Selenium Files/Save.jpg");
screen.Wait(Click_Save, 500);
screen.Click(Click_Save);
launcher.Stop();
}
}
}
Update your path of .jpg file in below line of code:
Pattern Click_Save = new Pattern("C:\\Selenium Files\\Save.jpg");
Rest of the code seems fine.

MultiThreading Variables C# -- Selenium

I am trying to automate the test for one of my websites using Selenium on C#. The website prompts the user for login credentials. It can only be done through multi threading.
I execute one thread to open the page in a special FireFox profile and another thread in parallel to simulate the press of ENTER.
The problem is the if I don't use multi threading, the code stops at opening the page as the website is not completely opened.
The driver is initiated in the first thread created. However it has to be used in the main method.
How can I pass an object created in a method (executed by a thread) in the main function?
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;
using System.Threading;
using System.IO;
using OpenQA.Selenium.Interactions;
using System.Windows.Forms;
namespace CRMTest1WithSelenium
{
class Program
{
public static IWebDriver OpenPage()
{
IWebDriver driver = null;
string path = #"C:\Users\ntouma\AppData\Roaming\Mozilla\Firefox\Profiles\nuxgc36b.CRMTester";
FirefoxProfile ffprofile = new FirefoxProfile(path);
driver = new FirefoxDriver(ffprofile);
driver.Navigate().GoToUrl("http://www.example.com");
return driver;
}
public static void pressEnter()
{
Thread.Sleep(6000);
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
}
static void Main(string[] args)
{
IWebDriver driver2 = null;
driver2 = OpenPage();
// Thread driverCreation = new Thread(OpenPage);
// driverCreation.Start();
Thread login = new Thread(pressEnter);
login.Start();
Thread.Sleep(2000);
driver2.Manage().Window.Maximize();
IWebElement sales = driver2.FindElement(By.XPath("/html/body/div[4]/d"));
sales.Click();
IWebElement leads = driver2.FindElement(By.XPath("/html/body//div/div/ul/li[3]/span/span[2]/span/span[1]/span/a[1]"));
leads.Click();
Thread.Sleep(5000);
}
}
}
Well i don't understand your problem in 100%...
But i can suggest two solutions:
1) Use a static member that your login functions will use inside it.
2) Send a class(object) to the thread when you create one:
e.g:
var myObj = ...; Thread thread = new Thread(() => pressEnter(myObj)); thread.Start();

Categories

Resources