我正在学习WebDriver并试图查看demoaut网站上的链接.循环中的代码应该通过其标题识别“正在构建”页面,打印出第一行,然后返回到基本URL.但这不会因某种原因发生.它获得的第一个“正在建设中”链接(特色度假目的地)不被识别,提示打印错误的行,然后由于NoSuchElementException而不是返回它崩溃,因为它正在查找错误的链接页.为什么会这样?为什么它不根据“正在建设中”页面的标题行事?
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CheckLinks {
public static void main(String[] args) {
String baseUrl = "http://newtours.demoaut.com/";
System.setProperty("webdriver.gecko.driver", "C:\\Workspace_e\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String underConsTitle = "Under Construction: Mercury Tours";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl);
List<WebElement> linkElements = driver.findElements(By.tagName("a"));
String[] linkTexts = new String[linkElements.size()];
int i = 0;
//extract the link texts of each link element
for (WebElement e : linkElements) {
linkTexts[i] = e.getText();
i++;
}
//test each link
for (String t : linkTexts) {
driver.findElement(By.linkText(t)).click();
if (driver.getTitle().equals(underConsTitle)) {
System.out.println("\"" + t + "\""
+ " is under construction.");
} else {
System.out.println("\"" + t + "\""
+ " is working.");
}
driver.navigate().back();
}
driver.quit();
}
}
最佳答案 单击第一个链接后,即使您返回到页面,linkTexts中的所有引用也将变为陈旧…您需要做的是将所有href存储在List中,然后导航到每个href并检查页面的标题.
我会这样写的……
public class CheckLinks
{
public static void main(String[] args) throws UnsupportedFlavorException, IOException
{
String firefoxDriverPath = "C:\\Users\\Jeff\\Desktop\\branches\\Selenium\\lib\\geckodriver-v0.11.1-win32\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", firefoxDriverPath);
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
String baseUrl = "http://newtours.demoaut.com/";
driver.get(baseUrl);
List<WebElement> links = driver.findElements(By.tagName("a"));
List<String> hrefs = new ArrayList<>();
for (WebElement link : links)
{
hrefs.add(link.getAttribute("href"));
}
System.out.println(hrefs.size());
String underConsTitle = "Under Construction: Mercury Tours";
for (String href : hrefs)
{
driver.get(href);
System.out.print("\"" + href + "\"");
if (driver.getTitle().equals(underConsTitle))
{
System.out.println(" is under construction.");
}
else
{
System.out.println(" is working.");
}
}
driver.close();
driver.quit();
}
}