下面的脚本我必须验证页面上的链接。这是一个转折点,我需要验证此页面中的链接,并且需要单击每个链接,然后也验证该页面上的链接,但我需要排除在第一页中验证的链接。我实在不知道该怎么表现了。我最多可以单击链接并验证该页面中的链接,但是我应该使用什么代码来排除那些已经验证的链接。如果可以的话请帮忙。谢谢
package siteLinks;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LinksValidation {
private static WebDriver driver = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
String homePage = "http://www.safeway.com/Shopstores/Site-Map.page";
String url = "http://www.safeway.com/Shopstores/Site-Map.page";
HttpURLConnection huc = null;
int respCode = 200;
System.setProperty("webdriver.chrome.driver", "C:\\Users\\aaarb00\\Desktop\\Quotients\\lib\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(homePage);
List<WebElement> links = driver.findElements(By.tagName("a"));
Iterator<WebElement> it = links.iterator();
while(it.hasNext()){
url = it.next().getAttribute("href");
System.out.println(url);
if(url == null || url.isEmpty()){
System.out.println("URL is either not configured for anchor tag or it is empty");
continue;
}
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode >= 400){
System.out.println(url+" is a broken link");
}
else{
System.out.println(url+" is a valid link");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
driver.quit();
}
}
最佳答案
您可以将已访问过的链接存储在 ArrayList 中,并检查该 ArrayList 是否已包含该链接。
ArrayList<String> visitedLinks = new ArrayList<String>();
List<WebElement> elements = driver.findElements(By.tagName("a"));
for(WebElement element : elements) {
if(visitedLinks.contains(element.getAttribute("href"))) {
System.out.println("Link already checked. Not checking.");
} else {
visitedLinks.add(element.getAttribute("href"));
// Your link checking code
}
}
我不确定您如何检查您检查状态 200 OK 响应的页面的链接,但您可能应该为要检查链接的每个页面定义 URL,然后循环遍历那些网址。否则,您可能会退出正在检查链接的网站并逃到更广泛的互联网上。在这种情况下,您的测试可能永远无法完成。
关于java - 如何排除已验证的链接验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50221930/