![](/img/trans.png)
[英]How to construct a xpath or css locator to identify the element using Selenium and Java
[英]Selenium-Xpath-Java or CSS locator
帮我找出按钮“单击JS警报”的xpath
这是链接https://the-internet.herokuapp.com/javascript_alerts
我正在使用这个xpath
.//*[@id='content']/div/ul/li[1]/button
它没有显示任何此类元素。
这是使用的代码:
public void test() {
driver.get("the-internet.herokuapp.com/javascript_alerts");
WebElement element=driver.findElement(By.id("//button[text()='Click for JS Alert']"));
element.click();
}
您以错误的方式使用代码:
WebElement element=driver.findElement(By.id("//button[text()='Click for JS Alert']"));
只有在使用XPath
By.id
才能应用于具有指定id
属性的搜索元素。
您需要在下面使用:
WebElement element=driver.findElement(By.xpath("//button[text()='Click for JS Alert']"));
element.click();
使用此xpath: (//div[@class='example']/ul/li/button)[1]
您的代码将如下所示:
driver.get(""the-internet.herokuapp.com/javascript_alerts");
WebElement element=driver.findElement(By.xpath("(//div[@class='example']/ul/li/button)[1]"));
element.click();
// * [@@ id ='content'] / div / ul / li [1] / button对我有用。 你使用的是什么浏览器? 您如何验证?
试试下面的代码。
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//button[contains(text(), 'Click for JS Alert')]")).click();
Thread.sleep(2500);
Alert alert = driver.switchTo().alert();
System.out.println(driver.switchTo().alert().getText());
alert.accept();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.