Xpath无法使用selenium Web Driver

时间:2017-12-20 09:26:47

标签: java selenium xpath

我有一个问题,试图从以下网页识别xpath

http://smartchanneltech.com/top100canalti/

这是我想要识别的元素:https://imgur.com/a/ENOP1

这是我使用的xpath:/html/body/div/div/div[1]/h1/a

这是我使用的代码:

public WebElement Empresa (WebDriver driver, int Iterator) {

    //WebDriverWait wait = new WebDriverWait(driver, 10);

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div/div[1]/h1/a")));
    return driver.findElement(By.xpath("/html/body/div/div/div[1]/h1/a"));

    }

最后,这是错误日志:https://imgur.com/a/quFjg

我只是尝试driver.findElement(By.xpath("/html/body/div/div/div[1]/h1/a"));,但也没有工作。

请帮帮我吗?

3 个答案:

答案 0 :(得分:1)

它在iframe中。首先切换到框架并尝试识别它。

public WebElement Empresa (WebDriver driver, int Iterator) {
   driver.switchTo().frame(0);
   String xpath="/html/body/div/div/div[1]/h1/a";
   wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
   return driver.findElement(By.xpath(xpath));
}

答案 1 :(得分:0)

我已经更新了如下方法。 请用这个。

public WebElement Empresa (WebDriver driver, int Iterator) {

//WebDriverWait wait = new WebDriverWait(driver, 10);

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@src='https://www.rise.global/display/top100-canalti/latest/embeddable/cut/stripes']")));

driver.switchTo().frame(driver.findElement(By.tagName("iframe")));

WebElement elem = driver.findElement(By.className("lb-leaderboard-widget-wrapper"));
WebElement elemH1 = elem.findElement(By.tagName("h1"));
WebElement elemIWant = elem.findElement(By.tagName("a"));

System.out.println(elemIWant.getAttribute("innerHTML").toString());

return elemIWant;

}

让我知道您的反馈意见。

答案 2 :(得分:0)

如果您查看HTML DOMWebElement位于<iframe>内。因此,我们需要先使用正确的<iframe>切换到WebDriverWait,然后按以下方式找到WebElement

new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[@src='https://www.rise.global/display/top100-canalti/latest/embeddable/cut/stripes']")));
return driver.findElement(By.xpath("div[@class='lb-leaderboard-header']/h1/a[@class='lb-leaderboard-name']"));