Selenium Webdriver - Relative xpath - java

I am a beginner in Selenium. I do not have any hands on experience in it. Last month I had enrolled for a Selenium beginner to advanced course where I have few activities where I can do hands on.
I am stuck at a certain place. Let me explain my issue.
This is the activity description:
RelativeXpathLocator
URL: http://webapps.tekstac.com/Shopify/
Test Procedure:
Use the template code.
Don't make any changes in DriverSetup file.
Only in the suggested section add the code to,
Invoke the driver using getWebDriver() method defined in DriverSetup()
Identify the web element of the value 'SivaKumar' using xpath locator and return it.
Using the same web element, get the text and return it.
The code that I wrote for this:
//Add required imports
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
public class RelativeXpathLocator //DO NOT Change the class Name
{
static String baseUrl = "http://webapps.tekstac.com/Shopify/";
public WebDriver createDriver() //DO NOT change the method signature
{
DriverSetup ds = new DriverSetup();
return ds.getWebDriver();
//Implement code to create Driver from DriverSetup and return it
}
public WebElement getRelativeXpathLocator(WebDriver driver)//DO NOT change the method signature
{
WebElement l = driver.findElement(By.xpath("//*[#id="tbrow"]/td[3]"));
return (l);
/*Replace this comment by the code statement to get the Web element */
/*Find and return the element */
}
public String getName(WebElement element)//DO NOT change the method signature
{
//Get the attribute value from the element and return it
}
public static void main(String[] args){
RelativeXpathLocator pl=new RelativeXpathLocator();
//Add required code
}
}
Note: Stuck at Public Webelement getRelativeXpathLocator
Now after I typed the code and complied to check if it threw any error, I was able to see expect ")" ";" errors in the xpath line.
I've been struggling for hours to get this to work but in vain.
Please advice.
Thanks.

The error is double quotation " in xpath , so change the xpath
From
driver.findElement(By.xpath("//*[#id="tbrow"]/td[3]"));
To
driver.findElement(By.xpath("//*[#id='tbrow']/td[3]"));

Related

Selenium cannot find ul Element that is visible on Page

I'm currently testing an email service, and upon opening a list of options to filter email, I want to be able to automate clicking on an option in the list. The code for the list is:
However, selenium cannot find this element, even though I can find it by searching the HTML using CTRL+F. The code I'm currently using to try and find and click this list element is:
wait.until(ExpectedConditions.visibilityOfElementLocated(org.myorg.automation.Objects.ManageEmails.Locators.FilterList));
Select dropdown = new Select(driver.findElement(org.myorg.automation.Objects.ManageEmails.Locators.FilterList));
dropdown.selectByVisibleText("Unread");
The xpath of the list is:
/html/body/div[7]/div/div/div/div/div/div/ul
Any help would really be appreciated!!
The problem is that you don't have a select in this case and the: Select dropdown = new Select(); wont work. You'll need a custom method to select a value from that list
public class Testing {
public WebDriver driver;
#Test
public void TestSomething() {
driver = new ChromeDriver();
driver.get("<the url where this list is present>");
// assuming that the ul list is unique on the page if not find another way to get it
WebElement ulListParent = driver.findElement(By.xpath("//ul[contains(#class,'ms-ContextualMenu-list is-open')]"));
SelectBasedOnValue(ulListParent, "Unread");
driver.close();
}
public void SelectBasedOnValue(WebElement parentElement, String optionValue) {
parentElement.findElement(By.xpath(String.format("//li[text()='%s']", optionValue))).click();
}
}

Why doesn't Selenium find element by xpath?

When I run the following program, why is '0' printed to the console? I expected '1' to be printed since I expected the findElements() method to find a link using the xpath. Is the xpath expression incorrect? I got the expression using Firefox, Firebug, and Firepath, by selecting the link element and copying the given xpath.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.List;
public class SeleniumSearch {
static WebDriver driver = new FirefoxDriver();
public static void main(String[] args) {
try {
driver.get("http://www.google.co.uk/");
submitSearch("selenium");
getHit();
}
finally {
driver.close();
}
}
static void submitSearch(String search) {
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys(search);
searchBox.submit();
}
static void getHit() {
List<WebElement> hits = driver.findElements(By.xpath("html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[3]/div[2]/div/div/div/div[2]/div[1]/div/h3/a"));
System.out.println(hits.size());
}
}
Try putting the following as xpath instead of the actual path:
//*[#id="rso"]/div[2]/div[1]/div/h3/a
xpath("html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[3]/div[2]/div/div/div/div[2]/div[1]/div/h3/a")
That's wrong work with xpath, one little change on website and your code wouldn't work! try to do it more dynamic find the closest id or tag name and continue from there, can you share your html source?
I would use a simple xpath like html/body//h3/a.
You can also use FirePath extension of FireBug to build and evaluate xpaths.
Simplest xpath I could come up with for first link in google search:
(//h3/a)[1]

How to convert webelement to string in selenium using java? Please refers to detail section for more info

I created a POM for 'Create project' page
public static class addProjInfo_container
{
public static WebElement ProjName_txt(WebDriver driver)
{
element=driver.findElement(By.xpath("//label[text()='Project Name']/following-sibling::input"));
return element;
}
// and so on for every text field for adding project...
And I created a TestUtility class with method for waitForElement as show below
public final class TestUtility {
private static WebDriver driver;
public static void waitforElementXpath(final WebDriver driver,final int waitTime,final String xp)
{
WebDriverWait wait =new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xp)));
}
}
Now, in Test script I want to avoid using Thread.sleep() to wait for webelement to be ready to start performing actions.
so, I use
TestUtility.waitforElementXpath(driver,10,CreateProject_Page.addProjInfo_container.projName_txt(driver));
But,it displays error as
The method waitforElementXpath(WebDriver, int, String) in the type TestUtility is not applicable for the arguments (WebDriver, int, WebElement)
Kindly, let me know how to handle the issue.
Basically your want to reverse the By to get its string and you are using xpath
so change to this which return the String instead of WebElement
public static class addProjInfo_container {
public static String projName_txt(WebDriver driver) {
By by = By.xpath("//label[text()='Project Name']/following-sibling::input");
driver.findElement(by);
return getSelectorAsString(by);
}
public static String getSelectorAsString(By by) {
String str = by.toString();
return str.substring(str.indexOf(" ") , str.length());
}
// and so on for every text field for adding project...
}
hope this could help
This is really a convoluted way of trying to accomplish this task. Your ProjName_txt() method already has found the element because that's what it returns so you don't need to wait for it to appear by using waitforElementXpath(). I would recommend that you read some articles on OOP and classes before you write too much more code.
The best way is:
String name = driver.findElementByClassName("classnamesample").getText() ;
Just add .getText() in the last of xpath and receive this as String.

How do I write test to check the browser scrolls down using webdriver, testng?

I have a link that stays on same page but scrolls down the screen
if you go to websiste test.naimi.me and click here:
the link should scroll you down a little bit, how to test this action in selenium webdriver, i use testng and write in java.
EDIT:#Helping hands
package erjan.test.naimi.me;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.Assert;
public class SpecialistLoads {
WebDriver firefox ;
#Test
public void main() {
//By.xpath("//a[#href=\"/astana/\"]/img") )) ;
WebElement all_specs = firefox.findElement(By.xpath("//a[#href=\"/astana/#specialists\"]")) ;
all_specs.click();
String all_specalists_url = firefox.getCurrentUrl();
Assert.assertEquals(all_specs, all_specialists_url );
}
#BeforeMethod
public void beforeMethod() {
firefox = new FirefoxDriver() ;
firefox.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch the website
firefox.get("http://test.naimi.me");
}
#AfterMethod
public void afterMethod() {
firefox.quit();
}
}
The link the red arrow points to has html code:
a data-toggle="menu" href="/astana/#specialists">Все специалисты</a>
If link is not visible when page load then you can use isdisplayed method like below :
WebElement link = driver.findElement(By.xpath(yourlinkxpath"));
If(link.isDisplayed())
{
// Write code to click on link
}
else
{
// Write code to skip it
}
To find link element you can use Id , xpath , class anything.
To test it, I would make usage of an indirect check.
Verify if a botton element of the page is visible after activating the link. I am more comfortable with the python code but in java the call should be:
WebElement.isDisplayed() to check if an element is visible
isDisplayed() is the method used to verify presence of a web element
within the webpage. The method is designed to result a Boolean value
with each success and failure. The method returns a “true” value if
the specified web element is present on the web page and a “false”
value if the web element is not present on the web page.
Example:
boolean footer_loaded=driver.findElement(By.id(“footer”)).isDisplayed();
You can check the size of an element and its position relative to the viewport by Element.getBoundingClientRect(). You'll need to use driver.executeScript() for that.

sendkey() doesnt work in selenium webdriver

I tried to input phone numbers in the field but it gives me an error
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element
Here is the code:
driver.get("https://marswebtdc.tdc.vzwcorp.com/cdl/lte/fdr_llc/fdr.jsp?3gOr4g=4g");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[#id='content column']/table[1]/tbody/tr/td/form/b/table/tbody/tr/td/table/tbody/tr[2]/td[4]/input")).click();
driver.findElement(By.xpath("//*[#id='content column']/table[1]/tbody/tr/td/form/b/table/tbody/tr/td/table/tbody/tr[2]/td[4]/input")).clear();
driver.findElement(By.xpath("//*[#id='content column']/table[1]/tbody/tr/td/form/b/table/tbody/tr/td/table/tbody/tr[2]/td[4]/input")).sendKeys("9083071303");
this is internal site you cant load the page.
I assume the sendkey() doesnt work for this field. is there any element i can use instead sendkey().
Exception org.openqa.selenium.NoSuchElementException tells the element not present on page when action is performed.
This may be because of either XPATH is not correct or element is not appeared on page before action is called.
Please run code in debug mode to find exact problem.
Here is quick example of google search box. I have put wrong id to make code fail. In this case I get the exception. If we correct the id "gbqfq" the code works fine.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GoogleSearchUsingSelenium {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
try
{
WebElement searchBox = driver.findElement(By.id("gbqfq1")); //Incorrect ID here
searchBox.sendKeys("Cheese");
}
catch(Exception e){
System.out.println("Eelemnt Not Found : "+e.getMessage());
}
driver.close();
}
}

Categories