Selenium c#click by xpath

时间:2018-05-08 09:47:22

标签: c# selenium xpath

我想要的只是点击exacly span 1

示例让我们去youtube.com,然后在搜索器中写一些内容,最后点击第一个跨度:

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);

现在我想点击第一个链接但是这条路径:

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

向我们展示19个链接。我怎么写span 1? 我尝试了这个谎言

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

但这不起作用。 某些人可以通过改变这个xpath来指导如何只选择1个跨度吗?

3 个答案:

答案 0 :(得分:0)

试试这个 (// [@ ID = “描述文本”] /跨度)[1]

参考:XPath query to get nth instance of an element

希望这有帮助

答案 1 :(得分:0)

我会将所有项目存储在List中,并按照意愿进行迭代:

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

您可以执行以下操作,或者为每个循环使用所有项目:

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 
        }

或选择某个元素:

WebElement element = listItems.get(0).findElements(By.tagName("span"));
System.out.println(element.getText());

答案 2 :(得分:0)

试试这个 Xpath

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

您可以使用此代码:

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();