.NET Tests with Selenium, headless Chrome error - selenium

I've been trying to implement headless browser to my tests and I'm getting an error message that shows me this: "Unable to locate element: {"method":"id","selector":"my_id"}". This is the code that I'm working with:
[TestFixture]
class ClientesSystemTest
{
private ChromeOptions options;
private NewClientesPage page;
private IWebDriver driver;
public ClientesSystemTest()
{
options = new ChromeOptions();
options.AddArgument("--headless");
driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options);
page = new NewClientesPage(driver);
}
[Test]
public void CadastraCliente()
{
page.Visita();
page.Cadastra("Paulo", "Guedes", "00870021087", "Rua abcdwxyz, 14", 15);
driver.Close();
}
}
and this is the Cadastra method.:
public void Cadastra(string nome, string sobrenome, string cpf, string endereco, int idade)
{
IWebElement nomeCliente = driver.FindElement(By.Id("Nome"));
IWebElement sobrenomeCliente = driver.FindElement(By.Id("Sobrenome"));
IWebElement cpfCliente = driver.FindElement(By.Id("CPF"));
IWebElement enderecoCliente = driver.FindElement(By.Id("Endereco"));
IWebElement idadeCliente = driver.FindElement(By.Id("Idade"));
IWebElement estadoCivilCliente = driver.FindElement(By.Name("EstadoCivil"));
driver.FindElement(By.CssSelector("[value=Divorciado]")).Click();
nomeCliente.SendKeys(nome);
sobrenomeCliente.SendKeys(sobrenome);
cpfCliente.SendKeys(cpf);
enderecoCliente.SendKeys(endereco);
idadeCliente.SendKeys(idade.ToString());
nomeCliente.Submit();
}
I've tried everything by this point. The test runs normally without the headless feature. Does anyone have a solution for this error? Thanks.

My guess would be that your site shows different elements depending on the browser resolution. Typically the headless browser is a smaller setting so I'd make sure it's set to the same size you use when you test non-headless.

Related

When I execute selenium script, following it browser is being closed Automatically?

I am writing selenium script and It's working perfect but when code is running then my browser is automatically closed?
public static void main(String args[])
{
System.setProperty("webdriver.chrome.driver",
"./chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("URL");
String email = "EMAil";
String password = "123";
int ELEMENT_WAIT_TIME_SEC = 60;
WebDriverWait explicitWait = new WebDriverWait(driver, ELEMENT_WAIT_TIME_SEC);
String locator = "//input[#type='email'][#aria-label='Email']";
By findBy = By.xpath(locator);
WebElement Login = explicitWait.until(ExpectedConditions.elementToBeClickable(findBy));
Login.click();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].setAttribute('aria-invalid',true);", Login);
Login.sendKeys(email);
String plocator = "//input[#type='password'][#aria-label='Password']";
By findByp = By.xpath(plocator);
WebElement Password = explicitWait.until(ExpectedConditions.elementToBeClickable(findByp));
Password.click();
jse.executeScript("arguments[0].setAttribute('aria-invalid',true);", Password);
Password.sendKeys(password);
}
Check your code. May be you used driver.close() method to close the browser.
Just comment or delete that code and the browser will not close automatically.
I got over this error by using the Code Runner extension of VS Code instead of manually running node file-path.
Works well.
This is a case of browser version compatibility issue with chrome. so update your chromedriver.exe in sync with current version of Chrome browser.

find xpath for a repeated angularJs Item

how is possible to find the xpath for an angularJs element? for instance i discovered that all links in my page have the same xpath due to the repeated items in angularJs -->
.//*[#id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a
but i have 10 of element , they are differente for text, so i tried with `"
so i tried with contains but it never find it
.//[#id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(#aria-label='Creazione Prodotto')]"`
i use selenium, junit4 , firefox webDriver
this is my code
public class PB01_TTT {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
WebElement element;
#Before()
public void setUp() throws Exception {
FirefoxProfile fxProfile = new FirefoxProfile();
fxProfile.setPreference("browser.download.folderList", 2);
fxProfile.setPreference("browser.download.manager.showWhenStarting", false);
fxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
fxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/pdf, application/x-pdf, application/octet-stream");
fxProfile.setPreference("pdfjs.disabled", true);
driver = new FirefoxDriver(fxProfile);
baseUrl = "https://w8aon2bpm.replynet.prv:9443";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testPBO1TTT() throws Exception {
driver.get(baseUrl + "/ProcessPortal/login.jsp");
// driver.get(baseUrl + "/ProcessPortal/dashboards/SYSRP/RESPONSIVE_WORK");
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys("user");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("password");
String columnToDisplay=driver.findElements(By.xpath(".//*[#id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(#aria-label='Creazione Prodotto')]"));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
element = (WebElement) driver.findElements(By.xpath(columnToDisplayXpath));
Assert.assertNotNull(element);
it always return me a notFoundElement, any suggestions ?
Thank you
If you have 10 links, then there is a high chance they are different in a way even if the path is the same, in this case you need to construct an path based on the thing that is different.
For example: use href, text or other any part that differs
//a[contains(#href, 'part_of_href')]
//a[contains(text(), 'part_of_text')]
//a[#title='title']
//a[contains(#aria-label='Creazione Prodotto')]
If you need any help in getting the selector please add the html section of the links, you can change the url if needed.
Tip: avoid using absolute xpaths and attributes that do not suggest anything and they can change like: .//*[#id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(#aria-label='Creazione Prodotto')]"
This will give you a lot of work in the future.

selenium webdriver method findElement give Unable to locate element:

I'm new in testing with selenium (IDE and WebDriver) and Junit i'm facing this problem:
First , i'v learnt how to use selenium IDE with firefox plugin
I create a maven project in Eclipse
Then i used selenium IDE to export the code as java/junit4/webDriver
In eclipse i create a class with code crated by selenium IDE :
public class PB01_TTT {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
WebElement element;
#Before()
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://w8a.prv:9431";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test
public void testPBO1TTT() throws Exception {
driver.get(baseUrl + "/ProcessPortal/login.jsp");
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys("user");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.cssSelector("span.submit-text")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
String columnToDisplayXpath = "//html/body/div[2]/div/div/div[1]/div/div/div[2]/div[3]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a";
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(columnToDisplayXpath)));
element = driver.findElement(By.xpath(columnToDisplayXpath));
Assert.assertNotNull(element);
Now when i run my test as junit test all code works until the method --> driver.findElement . It gives to me this error
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//html/body/div[2]/div/div/div[1]/div/div/div[2]/div[3]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a"}
In debug the By.xpath retrieve the element, i'v tried also the By.cssSelector ,but nothig changed. It's the driver findelement that doesn't work.
Any help will be really appraciated

Selenium tests do not work on IE8

To test some of the legacy pages I need to execute few test cases against IE8. These same testcases run efficiently against IE10/11, FF, Chrome without any issue.
public void TypePassword(string password)
{
var element = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(
ExpectedConditions.ElementIsVisible(By.XPath("//input[#id='txtPassword']")));
//I also tried with just id and cssselector
element.Clear();
element.SendKeys(password);
}
I also tried
public void TypePassword(string password)
{
Password.Clear();
Password.SendKeys(password);
}
Interestingly,
public void TypeUsername(string username)
{
Username.Clear();
Username.SendKeys(username);
}
always work without any issue.
The IE driver configuration
var options = new InternetExplorerOptions { EnableNativeEvents = false};
options.AddAdditionalCapability("EnsureCleanSession", true);
Driver = new InternetExplorerDriver(options);
Seems like I am missing some configuration which is specific to IE8.
Also, confirmed zoom level and protected mode set up
Have you tried JavascriptExecutor ?
var element = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//input[#id='txtPassword']")));
((JavascriptExecutor)Driver).executeScript("arguments[0].value='"+password+"'", element);
It is difficult to find the element exists,
so u can go for the element count >1 using do while loop,
do
{
Thread.Sleep(500);
}while(driver.FindElements(By.Id("IDNAME")).Count>0);
Unless until, the count of the element gets, this do loop will execute and wait for the element to visible also

Authentication of id and password in selenium webdriver

I have 2 methods in my testcase.
method 1 :
[TestMethod]
public void AddUser()
{
firefox = new OpenQA.Selenium.Firefox.FirefoxDriver();
firefox.Navigate().GoToUrl("http://<code><code>domain</code></code>:44220/learn-language-online/");
firefox.FindElement(By.LinkText("Sign In")).Click();
firefox.FindElement(By.CssSelector("span.watermarkify-watermark-inner")).Click();
firefox.FindElement(By.Id("Username")).Clear();
firefox.FindElement(By.Id("Username")).SendKeys("rachana#prakashinfotech.com");
firefox.FindElement(By.Id("Password")).Clear();
firefox.FindElement(By.Id("Password")).SendKeys("123456");
firefox.FindElement(By.XPath("(//a[contains(text(),'Sign In')])[2]")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(90));
OpenQA.Selenium.Interactions.Actions builder = new OpenQA.Selenium.Interactions.Actions(firefox);
IWebElement elem = firefox.FindElement(By.ClassName("icon"));
builder.MoveToElement(elem).Build().Perform();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(40));
firefox.FindElement(By.LinkText("Manage Users")).Click();
firefox.FindElement(By.Id("FirstName")).Clear();
firefox.FindElement(By.Id("FirstName")).SendKeys("Kashyap");
firefox.FindElement(By.Id("LastName")).Clear();
firefox.FindElement(By.Id("LastName")).SendKeys("Khanna");
firefox.FindElement(By.Id("Password")).Clear();
firefox.FindElement(By.Id("Password")).SendKeys("123");
firefox.FindElement(By.Id("ConfirmPassword")).Clear();
firefox.FindElement(By.Id("ConfirmPassword")).SendKeys("123");
firefox.FindElement(By.Id("Email")).Clear();
firefox.FindElement(By.Id("Email")).SendKeys("kashyap#gmail.com");
new SelectElement(firefox.FindElement(By.Id("Languages"))).SelectByText("India");
new SelectElement(firefox.FindElement(By.Id("DifficultyLevels"))).SelectByText("Level 1");
new SelectElement(firefox.FindElement(By.Id("MaturityLevels"))).SelectByText("Everyone");
firefox.FindElement(By.XPath("//a[2]/span")).Click();
}
method 2 :
[TestMethod]
public void AssignCourse()
{
firefox = new OpenQA.Selenium.Firefox.FirefoxDriver();
firefox.Navigate().GoToUrl("http://<code>domain</code>:44220/Home/Index");
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(90));
OpenQA.Selenium.Interactions.Actions builder = new OpenQA.Selenium.Interactions.Actions(firefox);
IWebElement elem = firefox.FindElement(By.ClassName("icon"));
builder.MoveToElement(elem).Build().Perform();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(90));
firefox.FindElement(By.LinkText("Manage Users")).Click();
firefox.FindElement(By.XPath("//div[#id='divUser_84700']/div[2]/div/div/a[2]")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(120));
firefox.FindElement(By.XPath("(//img[#alt='Delete'])[5]")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(80));
firefox.FindElement(By.XPath("//a[#id='addCourses']/span")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(80));
firefox.FindElement(By.CssSelector("li.class_73.courseItem > a > span.detail")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(40));
firefox.FindElement(By.CssSelector("li.class_87.courseItem > a > span.detail")).Click();
firefox.FindElement(By.Id("btnAddCourse")).Click();
}
now when my 1st method get tested and it moves to 2nd method session of uesrid and password not get maintained and because of that i am not able to navigate my url to http://domain:44220/Home/Index. so how to solve the issue of authentication.
Specify firefox = new OpenQA.Selenium.Firefox.FirefoxDriver();
in a setup method may be in #BeforeTest, it makesures that there is only one instance of firefoxdriver is running for the entire set of tests.
You have at least two options.
You can use cookie:
Cookie ck = new Cookie("name", "value");
driver.manage().addCookie(ck);
(code in java)
Operation on cookie - http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/Cookie.html
You can use Page Object Pattern it is best practice to create test code. You can then call method to log in from #Before or #BeforeTest annotation etc. I encourage you to reaad about Page Object Pattern because it helps writing maintanable, and cleaner test code
WebDriver creates a new Firefox profile every time you launch the browser so any cookies or whatever session parameters are lost. Meaning, you have to log in again. That would be:
private WebDriver firefox;
private void LogIn()
{
firefox = new OpenQA.Selenium.Firefox.FirefoxDriver();
firefox.Navigate().GoToUrl("http://<code><code>domain</code></code>:44220/learn-language-online/");
firefox.FindElement(By.LinkText("Sign In")).Click();
firefox.FindElement(By.CssSelector("span.watermarkify-watermark-inner")).Click();
firefox.FindElement(By.Id("Username")).Clear();
firefox.FindElement(By.Id("Username")).SendKeys("rachana#prakashinfotech.com");
firefox.FindElement(By.Id("Password")).Clear();
firefox.FindElement(By.Id("Password")).SendKeys("123456");
firefox.FindElement(By.XPath("(//a[contains(text(),'Sign In')])[2]")).Click();
}
[TestMethod]
public void AddUser()
{
LogIn();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(90));
OpenQA.Selenium.Interactions.Actions builder = new OpenQA.Selenium.Interactions.Actions(firefox);
IWebElement elem = firefox.FindElement(By.ClassName("icon"));
builder.MoveToElement(elem).Build().Perform();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(40));
firefox.FindElement(By.LinkText("Manage Users")).Click();
firefox.FindElement(By.Id("FirstName")).Clear();
firefox.FindElement(By.Id("FirstName")).SendKeys("Kashyap");
firefox.FindElement(By.Id("LastName")).Clear();
firefox.FindElement(By.Id("LastName")).SendKeys("Khanna");
firefox.FindElement(By.Id("Password")).Clear();
firefox.FindElement(By.Id("Password")).SendKeys("123");
firefox.FindElement(By.Id("ConfirmPassword")).Clear();
firefox.FindElement(By.Id("ConfirmPassword")).SendKeys("123");
firefox.FindElement(By.Id("Email")).Clear();
firefox.FindElement(By.Id("Email")).SendKeys("kashyap#gmail.com");
new SelectElement(firefox.FindElement(By.Id("Languages"))).SelectByText("India");
new SelectElement(firefox.FindElement(By.Id("DifficultyLevels"))).SelectByText("Level 1");
new SelectElement(firefox.FindElement(By.Id("MaturityLevels"))).SelectByText("Everyone");
firefox.FindElement(By.XPath("//a[2]/span")).Click();
}
[TestMethod]
public void AssignCourse()
{
LogIn();
firefox.Navigate().GoToUrl("http://<code>domain</code>:44220/Home/Index");
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(90));
OpenQA.Selenium.Interactions.Actions builder = new OpenQA.Selenium.Interactions.Actions(firefox);
IWebElement elem = firefox.FindElement(By.ClassName("icon"));
builder.MoveToElement(elem).Build().Perform();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(90));
firefox.FindElement(By.LinkText("Manage Users")).Click();
firefox.FindElement(By.XPath("//div[#id='divUser_84700']/div[2]/div/div/a[2]")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(120));
firefox.FindElement(By.XPath("(//img[#alt='Delete'])[5]")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(80));
firefox.FindElement(By.XPath("//a[#id='addCourses']/span")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(80));
firefox.FindElement(By.CssSelector("li.class_73.courseItem > a > span.detail")).Click();
firefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(40));
firefox.FindElement(By.CssSelector("li.class_87.courseItem > a > span.detail")).Click();
firefox.FindElement(By.Id("btnAddCourse")).Click();
}