[英]How to get title by xpath?
有没有办法通过driver.getTitle()
xpath获取标题
我尝试了以下方法: By.xpath("//title")
但它没有用。 例如StackOverflow
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元素
我看不出您不想使用driver.getTitle()
但是,如果必须使用xpath,则可以执行以下操作:
driver.findElement(By.xpath("//title")).getText();
更新
根据更新的问题似乎,失败是在
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//title")));
要解决此问题,我建议等待时间超过0
秒,然后将visibilityOfElementLocated
更改为presenceOfElementLocated
。
理想情况下,您应该使用ExpectedConditions.titleIs()
有关可用选项的更多信息,可在此处找到。
该问题似乎与浏览器有关。 以下代码在FF 3.6上产生了正确的输出,但在IE 9和Chrome 31中都没有这样做(空字符串)。
WebElement title = driver.findElement(By.xpath("//title"));
System.out.println(title.getText());
如果您真的不想使用getTitle()
它应该可以在任何浏览器上使用:
title.getAttribute("innerHTML");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.