gpt4 book ai didi

java - Selenium 网络驱动程序 : how to verify that there is a heading titled “Download” on the page wrapped in

tags?

转载 作者:行者123 更新时间:2023-12-02 05:33:51 25 4
gpt4 key购买 nike

我应该使用哪个断言?请举个例子好吗?

代码当前打开 selenium 网站并单击“下载”链接。

在下载页面上有一个名为“下载”的 h2 标题。

<h2>Downloads</h2>

如何验证是否存在包含文本“下载”的标题并且该标题被 h2 标签包围?

如果我无法将断言行添加到“测试”方法中,请您帮我弄清楚如何在下面的代码中创建和调用所需的方法。我是java和selenium的新手。感谢您提供的任何帮助。

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class guayaki {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();

@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.seleniumhq.org/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testGuayaki() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.linkText("Download")).click();
}

@After
public void tearDown() throws Exception {
//driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}

private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}

private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}

最佳答案

您可以使用 xpath 和 findElements 来实现此目的:

@Test
public void testGuayaki() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.linkText("Download")).click();

List<WebElement> downloadHeader = driver.findElements(By.xpath("//h2[contains(text(), 'Downloads')]"));
if(downloadHeader.size() > 0)
{
System.out.println("Found h2 header Downloads");
}
}

如果要进行精确匹配,可以修改xpath如下:

//h2[text() = 'Downloads']

关于java - Selenium 网络驱动程序 : how to verify that there is a heading titled “Download” on the page wrapped in <h2> tags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25230226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com