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]
Related
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]"));
The first part of the code work will work. But the second part doesn't work, and no error appears, and I don't know where the problem is. So please help.
First part is the login page, and the second part is home page.
package Test;
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.chrome.ChromeDriver;
public class test {
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
System.setProperty("webdriver.gecko.driver",
"E:\\Quality\\drivers\\geckodriver.exe");
driver =new FirefoxDriver();
driver.get("https://www.linkedin.com/uas/login");
// first part//
driver.findElement(By.xpath("//*[#id=\"session_key-login\"]")).click();
driver.findElement(By.xpath("//[#id=\"session_keylogin\"]")).sendKeys("Email");
driver.findElement(By.xpath("//*[#id=\"session_password-login\"]")).click();
driver.findElement(By.xpath("//*[#id=\"session_password-login\"]")).sendKeys("*******");
driver.findElement(By.xpath("//*[#id=\"btn-primary\"]")).click();
// second part//
WebElement test = null ;
test.findElement(By.xpath("/html/body/div[5]/div[5]/aside/div/header")).click();
}
}
You have putted a wrong id for xpath of email textbox.
You should use session_key-login instead of session_keylogin.
Just use the below revised code where you're using sendKeys() method:
driver.findElement(By.xpath("//*[#id=\"session_key-login\"]")).sendKeys("Email");
2nd part Solution
Skip WebElement declaration, thus comment the line //WebElement test = null;
Use the line using driver object
driver.findElement(By.xpath("/html/body/div[5]/div[5]/aside/div/header")).click();
You can also use xpath //*[#id=\"msg-overlay\"]/div/header
thus for the revised code is:
driver.findElement(By.xpath("//*[#id=\"msg-overlay\"]/div/header")).click();
Trying to get the script to select the filter button on the top but can't seem to figure out how to input the XPath. I believe it has something to do with it be in a separate iframe.
package chromebrowser;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class JavaClass {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Newfolder\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://mlvtwrew73.consilio.com/Relativity/");
driver.manage().window().maximize();
//Thread.sleep(5000); this can be used as a wait command before moving on to the next function
WebElement objWE;
Thread.sleep(9000);
// objWE = driver.findElement(By.linkText("User Status"));
// objWE.click();
driver.switchTo().defaultContent();
driver.findElement(By.xpath("id(\"ctl00_ctl00_itemList_FilterSwitch\")")).click();
// objWE = driver.findElement(By.id("1"));
// driver.close(); will be used to close the site once all testing completes
}
}
Use ID locator -- it's more appropriate here (and faster than XPath):
WebDriverWait wait= new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.elementToBeClickable(By.id("ctl00_ctl00_itemList_FilterSwitch")));
driver.findElement(By.id("ctl00_ctl00_itemList_FilterSwitch")).click();
Looks like you're passing in an incorrect XPath. Try this one:
driver.findElement(By.xpath("//a[#id='ctl00_ctl00_itemList_FilterSwitch']")).click();
If there is then why you are using xpath.
Use id like this
driver.findElment(By.id("ctl00_ctl00_itemList_FilterSwitch"). click ();
I need more clarity regarding your question.
As I have understand, I think you need a requirement of XPath of the Filters image. If i am right, try this:
//div[#class='actionCellContainer']//a/img[#class='itemListActionImage']
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.
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();
}
}