Why can't Selenium Web Driver find the elements in this case? - selenium-webdriver

Selenium newbie here. The examples I tried so far worked well but now I stumbled upon a case that seemingly doesn't work:
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GeckoDriverTest
{
public static void main(String[] args) throws Throwable
{
System.setProperty("webdriver.gecko.driver", "D://XXX/seleniumdrivers/geckodriver.exe");
FirefoxDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.aerzen.com/de/karriere/stellenangebote.html");
System.out.println("URL = "+driver.getCurrentUrl());
Thread.sleep(3000);
driver.findElement(By.cssSelector("a.consent-banner--accept.button.submit")).click();
Thread.sleep(3000);
System.out.println("URL = "+driver.getCurrentUrl());
List<WebElement> elements = driver.findElements(By.cssSelector("tr > td > a"));
System.out.println("Elements: "+elements.size());
for(WebElement element : elements)
{
String url = element.getAttribute("href");
System.out.println(url);
}
}
}
The first part does work but the "tr > td > a" selector doesn't find any elements although I'm pretty sure they exist (I can see them in the browser window).
Any idea what's going wrong there? Thanks a lot.

The table is inside an iframe. In order to access these elements you will need to switch to that iframe.
Also instead of tr > td > a cssSelector try using table td.real_table_col1 a cssSelector.
This should work better:
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//iframe")));
driver.switchTo().frame(driver.findElement(By.xpath("//iframe")));
List<WebElement> elements = driver.findElements(By.cssSelector("table td.real_table_col1 a"));
System.out.println("Elements: "+elements.size());
for(WebElement element : elements)
{
String url = element.getAttribute("href");
System.out.println(url);
}
Also instead of hardcoded pauses like
Thread.sleep(3000);
You should use ExpectedConditions something like
WebdriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.consent-banner--accept.button.submit")));

Related

Unable to locate element using ID or Name

HTML:
<input name="txtAnswer" type="text" maxlength="20" id="txtAnswer" class="box1">
Code trials:
driver.findElement(By.xpath("//table[#id='tblSecurityAnswer']//tbody//tr[2]//td[2]//input[#id='txtAnswer']")).sendKeys("green");
and also:
driver.findElement(By.cssSelector("//tr:nth-child(1) > td > table > tbody >
// tr:nth-child(2) > td:nth-child(2)"));
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
// IE webdriver
// System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
// driver = new InternetExplorerDriver();
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver();
// Maximize the browser window
driver.manage().window().maximize();
// navigate to specified url
driver.get("http://dxbqcapp01/molforms/login.aspx");
driver.findElement(By.id("txtUserName")).sendKeys("MS200963915");
driver.findElement(By.id("txtPassword")).sendKeys("test#123");
driver.findElement(By.xpath("//input[#type='submit' and #value='Submit']")).sendKeys(Keys.ENTER);
driver.findElement(By.id("txtAnswer")).sendKeys("green");
The error stack trace would have helped us to debug your issue in a better way. However to send a character sequence to the desired element you have to induce WebDriverWait for the element to be clickable and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.box1#txtAnswer"))).sendKeys("green");
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#class='box1' and #id='txtAnswer']"))).sendKeys("green");

Trying to automate gmail signup page using selenium webdriver in java

This is how far I have been. But, I am having hard time automating the texts that are in drop-down menu. I tried to automate using select statements, but with no success. I used select while automating facebook signup page and it worked. Following is the code I used during the process
package signUp;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
import java.util.List;
/**
* Created by san on 4/18/17.
*/
public class LoginCredintials {
#Test
public void GoogleSignup(){
System.setProperty("webdriver.gecko.driver", "/Users/abc/Downloads/geckodriver");
WebDriver driver = new FirefoxDriver();
String baseUrl = "https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ltmpl=default";
driver.get(baseUrl);
//By ID Text area1
WebElement text1 = driver.findElement(By.id("FirstName"));
text1.clear();
text1.sendKeys("San ");
WebElement text2 = driver.findElement(By.id("LastName"));
text2.clear();
text2.sendKeys("P");
WebElement text3 = driver.findElement(By.xpath(".//*[#id='GmailAddress']"));
text3.clear();
text3.sendKeys("s20077");
WebElement text4 = driver.findElement(By.xpath(".//*[#id='Passwd']"));
text4.clear();
text4.sendKeys("123abcdxy");
WebElement text5 = driver.findElement(By.xpath(".//*[#id='PasswdAgain']"));
text5.clear();
text5.sendKeys("123abcdxy");
WebElement text6 = driver.findElement(By.id("BirthDay"));
text6.clear();
text6.sendKeys("1");
WebElement text7 = driver.findElement(By.id("BirthYear"));
text7.clear();
text7.sendKeys("2000");
WebElement text8 = driver.findElement(By.id("RecoveryPhoneNumber"));
text8.clear();
text8.sendKeys("9222103436");
WebElement text9 = driver.findElement(By.id("RecoveryEmailAddress"));
text9.clear();
text9.sendKeys("abc_gh#yahoo.com");
Select droplist1 = new Select(driver.findElement(By.id("gender")));
droplist1.selectByVisibleText("Male");
Select droplist2 = new Select(driver.findElement(By.id("BirthMonth")));
droplist2.selectByVisibleText("March");
Select droplist3 = new Select(driver.findElement(By.xpath(".//*[#id='CountryCode']/div")));
droplist3.selectByVisibleText("United States");
WebElement text10 = driver.findElement(By.id("submitbutton"));
text10.click();
}
}
You will have to write a custom method for selecting values from the required drop-downs, as they are not standard select components. Hence, you need to first click on the dropdown and wait for the options to appear. Once, the options are visible, you can click on the required option. I have written a generic method 'googleSelect' for this purpose below:
package signUp;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
/**
* Created by san on 4/18/17.
*/
public class LoginCredintials {
static WebDriver driver = null;
#Test
public void GoogleSignup(){
System.setProperty("webdriver.gecko.driver", "/Users/abc/Downloads/geckodriver");
driver = new FirefoxDriver();
String baseUrl = "https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ltmpl=default";
driver.get(baseUrl);
//By ID Text area1
WebElement text1 = driver.findElement(By.id("FirstName"));
text1.clear();
text1.sendKeys("San ");
WebElement text2 = driver.findElement(By.id("LastName"));
text2.clear();
text2.sendKeys("P");
WebElement text3 = driver.findElement(By.xpath(".//*[#id='GmailAddress']"));
text3.clear();
text3.sendKeys("s20077444");
WebElement text4 = driver.findElement(By.xpath(".//*[#id='Passwd']"));
text4.clear();
text4.sendKeys("123abcdxy");
WebElement text5 = driver.findElement(By.xpath(".//*[#id='PasswdAgain']"));
text5.clear();
text5.sendKeys("123abcdxy");
WebElement text6 = driver.findElement(By.id("BirthDay"));
text6.clear();
text6.sendKeys("1");
WebElement text7 = driver.findElement(By.id("BirthYear"));
text7.clear();
text7.sendKeys("2000");
WebElement text8 = driver.findElement(By.id("RecoveryPhoneNumber"));
text8.clear();
text8.sendKeys("9222103436");
WebElement text9 = driver.findElement(By.id("RecoveryEmailAddress"));
text9.clear();
text9.sendKeys("abc_gh#yahoo.com");
googleSelect(By.id("Gender"), "Male");
googleSelect(By.id("BirthMonth"), "March");
googleSelect(By.xpath(".//*[#id='CountryCode']/div"), "United States");
WebElement text10 = driver.findElement(By.id("submitbutton"));
text10.click();
driver.quit();
}
private static void googleSelect(By by, String text) {
driver.findElement(by).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOf(
driver.findElement(By.xpath("//div[#class='goog-menu goog-menu-vertical']//div[text()='" + text + "']"))));
driver.findElement(By.xpath("//div[#class='goog-menu goog-menu-vertical']//div[text()='" + text + "']")).click();
}
}
Try above code and let me know, if it works for you.
Check the html side of the page. Sometimes check boxes are written as links. So you have to click on the drop down first and click on the element you have to select. I may not be right but if you can please check.
just saw the signup page. looks like it's made up div and li elements so Select won't work. i also saw values being set into hidden fields like "HiddenGender", "HiddenBirthMonth". try developer tools inspect element on chrome to get the fields you require and set the values to these hidden elements directly. Hope this helps.

Selenium WebDriver using JavaScript

I'm new to Selenium WebDriver and trying to automate the online shopping site "amazon.co.uk". My intention is to navigate to a particular page of the site and retrieve the sellers names,their respective URL's and write the final output to an Excel Sheet. I was able to print all the above mentioned details in the console but couldn't write them into an Excel Sheet.
Below is the piece of code that I had come up with:
package Selenium.src.com.amazon.automation;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class AmazonTest {
public static void main(String[] args) throws InterruptedException, IOException {
WebDriver driver = new FirefoxDriver();
try {
driver.get("https://www.amazon.co.uk");
Thread.sleep(1000);;
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(150, TimeUnit.SECONDS);
String PageTitle = driver.getTitle();
System.out.println("Page Title is :" + PageTitle );
} catch (Exception e) {
e.printStackTrace();
System.out.println("Driver not reachable");
}
WebElement wb = driver.findElement(By.xpath("//span[text()='Shop by']"));
WebElement wb1 = driver.findElement(By.xpath("//span[text()='Electronics & Computers']"));
Actions act = new Actions(driver);
act.moveToElement(wb).build().perform();
act.moveToElement(wb1).build().perform();
driver.findElement(By.xpath("//span[text()='Headphones']")).click();
Thread.sleep(2000);
// To wait until the next page loads
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, 1000);");
driver.findElement(By.xpath("(//span[text()='See more'])[2]")).click();
List<WebElement> topSellers = driver.findElements(By.xpath("//div[#id='refinementList']//a"));
// int sellersCount = topSellers.size();
System.out.println("The Number Of Top Sellers is :" + topSellers.size());
for(int i=0;i<topSellers.size();i++)
{
//To print the list of Top Sellers and their number of products
System.out.println(topSellers.get(i).getText());
//To print the link of individual seller
System.out.println(topSellers.get(i).getAttribute("href"));
/*To get the page title for individual seller
String PageTitle = driver.getTitle();
System.out.println("Page Tile for this seller is :" +PageTitle);
topSellers.get(i).click();
Thread.sleep(2000);
driver.navigate().back();
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleIs("Amazon.co.uk: see all sellers"));
driver.navigate().refresh();*/
}
driver.close();
}
}
Can anybody please help me to achieve this requirement
I'm trying to write the below mentioned data into the Excel sheet...
1. Seller Name
2. Number of products of the seller
3. href link for individual seller
Please find the Screenshot for the same.
Image shows the list of TopSellers and the count of their products

Not able to Click a Link in Gmail using Selenium Webdriver

I am a learner.
I am trying to automate the logout functionality of Gmail using Selenium Webdriver but unable to do so ..
There are two Phases in logout, first click the Right Link at the top, if that box appears then click logout. iam unable to do so.
<span id="gbi4t" style="max-width: 76px; text-align: left;">Mahmood Ali</span>
<a id="gb_71" class="gbqfbb" href="?logout&hl=en&hlor" onclick="gbar.logger.il(9,{l:'o'})" role="button" target="_top">Sign out</a>
here is my xpath
//*[#id="gbi4t"] -> Clicking that top to get the logout pop up
//*[#id="gb_71"] -> To logout the gmail application
i have tried such as
driver.findElement(By.id("gbi4t")).click(); OR
driver.findElement(By.xpath("//*[#id='gbi4t']")).click();
driver.findElement(By.id("gb_71")).click(); OR
driver.findElement(By.xpath("//*[#id='gb_71']")).click();
Some ideas out there ?
Actually the <span> isn't recognized as an element.
You need to use the <a id="gbg4" ...> to click() on it, wait the pop up and click on the <a id="gb_71" class="gbqfbb" ...> to logout.
I let you code, since you need to pracctice :P
tell me what's up.
Suggestions :
What i can suggest to you is to use the cssSelector().
why ? Because it's faster than the xpath and when page like google or others use dynamic value used for id/name it's better to use the class attribute and cssSelector() is way better than others.
But sometimes you'll use xpath to find an element that has "cancel" as inner text (exemple : <a>cancel</a> )
cssSelector() reference
You can also try following:
driver.find_element(:id, "gbgs4dn").click
driver.find_element(:id, "gb_71").click
This worked for me.
This code certainly works for me:
// (after logging to google.com)
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("gbi4t")));
//open overlay
driver.findElement(By.id("gbi4t")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("gb_71")));
//press logout
driver.findElement(By.id("gb_71")).click();
Heres a solved example ::
package testme;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class testexample {
public static WebDriver driver;
public static WebElement element;
public static void main(String args[]) throws InterruptedException {
//setting the chrome driver
System.setProperty("webdriver.chrome.driver", "C:/Users/workspace/Downloads/chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.gmail.com");
element =driver.findElement(By.linkText("Sign in"));
element.click();
Thread.sleep(1000);
element = driver.findElement(By.id("Email"));
element.sendKeys("yourusername#gmail.com");
element = driver.findElement(By.id("Passwd"));
element.sendKeys("yourpassword");
element.submit();
Thread.sleep(1000);
//click on the logout link step 1
element = driver.findElement(By.xpath("//*[#id='gb']/div[1]/div[1]/div/div[3]/div[1]/a"));
element.click();
// click on actual logout button step 2
element = driver.findElement(By.id("gb_71"));
element.click();
//closing the webdriver window after successful completion of the test
driver.close();
}
}

Unable to find a link while running Selenium Test case

I am using Selenium webdriver. I can log in to the application, but while logging out it gets stuck, reason it cannot find logout link. I tried to find it byLink and byId. I have also tried using thread.sleep() but nothing seems to be working.
Logout link is present in all the pages.
HTML code:
<li>#{loginView.loggedInUser}>
<ul><li><h:link value="Administration" outcome="Administration.xhtml" /></li>
<li><h:commandLink value="Logout" actionListener="#{loginView.logout}">
<f:param id="userName" value="#{loginView.username}" />
</h:commandLink></li>
</ul></li>
SELENIUM code:
Thread.sleep(5000);
WebElement logOut = findElementByLinkText("Logout");
logOut.click();
assertEquals("Please sign in: ", findElementBySelector("h3.loginTitle.centerAlign").getText());
Use this code check how many links are present on page if it contains your logout link then you can click on it by using locator "linktext".
public void Link(){
driver.get(baseUrl);
HtmlTagFinder links = LinkFinder.links();
List<WebElement> allLinks = (List<WebElement>) links.findFrom(driver);
System.out.println(allLinks.size());
int i = 1;
for(WebElement link : allLinks){
System.out.println(i);
System.out.println(link.getText());
i++;
}
driver.close();
driver.quit();
}
driver.findElement(By.xpath("#value='Logout'")).click();

Resources