-1

All i want is to just click exacly span 1

Example let's go to youtube.com , then write something in searcher and finally click 1st span like this:

driver.Navigate().GoToUrl("https://youtube.com");
driver.FindElement(By.XPath("//*[@id='search']")).SendKeys("I should be so lucky");
driver.FindElement(By.XPath("//*[@id='search']")).SendKeys(Keys.Return);

And now i want click 1st link but this path :

//*[@id="description-text"]/span

show us 19 links . How can i write span 1? I try something liek this

//*[@id="description-text"]/span[1]

but this doesn't works. Can somene heelp how to choose exacly only 1 span by changing this xpath?

Adam Zbudniewek
  • 107
  • 2
  • 12

3 Answers3

1

try this
(//[@id="description-text"]/span)[1]

REF :XPath query to get nth instance of an element

Hope this helps

Pierre Baran
  • 160
  • 10
0

I would store all items in List and iterate upon will, like so:

List<WebElement> listItems = driver.findElements(By.id("description-text"));

than You can do following, or itterate all items with for each loop:

for (WebElement element :listItems) {
            //... do whatever You need to do with element
            element.findElements(By.tagName("span")); // so this is Your span, or all spans 
        }

or select certain element:

WebElement element = listItems.get(0).findElements(By.tagName("span"));
System.out.println(element.getText());
Kovacic
  • 1,473
  • 6
  • 21
0

Try this Xpath :

//h3[contains(@class,'ytd-video-renderer')]/a[contains(@aria-label,'Kylie Minogue - I Should Be So Lucky by HCAESAR 10 years ago ')]  

You can use this code :

driver = new ChromeDriver();
wait =new WebDriverWait(driver, 10);
driver.manage().window().maximize();
driver.get("https://www.youtube.com/");
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div[id='search-input']>input")));
driver.findElement(By.cssSelector("div[id='search-input']>input")).sendKeys("I should be so lucky"+Keys.RETURN);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("primary")));
WebElement links =  wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//h3[contains(@class,'ytd-video-renderer')]/a[contains(@aria-label,'Kylie Minogue - I Should Be So Lucky by HCAESAR 10 years ago ')]")));
links.click();
cruisepandey
  • 28,520
  • 6
  • 20
  • 38