0

有没有办法通过 xpath insted 获得标题driver.getTitle()

我尝试了以下方法: By.xpath("//title")

但它没有用。例如堆栈溢出

public class TestStack {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "chromedriver\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://stackoverflow.com/");
        WebDriverWait wait = new WebDriverWait(driver, 60);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//title")));

        System.out.println(driver.findElement(By.xpath("//title")).getText());
    }

}

未找到 xpath 的元素

4

2 回答 2

2

我看不出你不想使用的理由driver.getTitle()

但是如果你必须使用 xpath,你可以这样做:

driver.findElement(By.xpath("//title")).getText();

更新

根据更新后的问题,好像失败在

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//title")));

要修复它,我建议等待超过0几秒的时间,然后更改 visibilityOfElementLocatedpresenceOfElementLocated.

理想情况下,您应该使用ExpectedConditions.titleIs() 有关可用选项的更多信息,可以在此处找到。

于 2013-08-30T18:37:01.003 回答
2

问题似乎与浏览器有关。以下代码在 FF 3.6 上产生了正确的输出,但在 IE 9 和 Chrome 31 中都没有这样做(空字符串)。

WebElement title = driver.findElement(By.xpath("//title"));         
System.out.println(title.getText());

如果您真的不想使用getTitle()它应该可以在任何浏览器上使用:

title.getAttribute("innerHTML");
于 2013-08-30T20:21:03.050 回答