我想验证网站上的损坏链接,并且我正在使用以下代码:
public static int invalidLink;
String currentLink;
String temp;
public static void main(String[] args) throws IOException {
// Launch The Browser
WebDriver driver = new FirefoxDriver();
// Enter URL
driver.get("http://www.applicoinc.com");
// Get all the links URL
List<WebElement> ele = driver.findElements(By.tagName("a"));
System.out.println("size:" + ele.size());
boolean isValid = false;
for (int i = 0; i < ele.size(); i++) {
isValid = getResponseCode(ele.get(i).getAttribute("href"));
if (isValid) {
System.out.println("ValidLinks:" + ele.get(i).getAttribute("href"));
driver.get(ele.get(i).getAttribute("href"));
List<WebElement> ele1 = driver.findElements(By.tagName("a"));
System.out.println("InsideSize:" + ele1.size());
for (int j=0; j<ele1.size(); j++){
isValid = getResponseCode(ele.get(j).getAttribute("href"));
if (isValid) {
System.out.println("ValidLinks:" + ele.get(j).getAttribute("href"));
}
else{
System.out.println("InvalidLinks:"+ ele.get(j).getAttribute("href"));
}
}
} else {
System.out.println("InvalidLinks:"
+ ele.get(i).getAttribute("href"));
}
}
}
}
public static boolean getResponseCode(String urlString) {
boolean isValid = false;
try {
URL u = new URL(urlString);
HttpURLConnection h = (HttpURLConnection) u.openConnection();
h.setRequestMethod("GET");
h.connect();
System.out.println(h.getResponseCode());
if (h.getResponseCode() != 404) {
isValid = true;
}
} catch (Exception e) {
}
return isValid;
}
}
我会让它返回一个 int,并且只让 MalformedURLException 成为一个特殊情况,返回 -1。
public static int getResponseCode(String urlString) {
try {
URL u = new URL(urlString);
HttpURLConnection h = (HttpURLConnection) u.openConnection();
h.setRequestMethod("GET");
h.connect();
return h.getResponseCode();
} catch (MalformedURLException e) {
return -1;
}
}
编辑:看来您坚持使用布尔方法,正如我之前所说,它有其局限性,但对于演示目的来说应该可以正常工作。
没有理由采用您所采用的方法第二次找到所有元素。尝试这个:
// Get all the links
List<WebElement> ele = driver.findElements(By.tagName("a"));
System.out.println("size:" + ele.size());
boolean isValid = false;
for (int i = 0; i < ele.size(); i++) {
string nextHref = ele.get(i).getAttribute("href");
isValid = getResponseCode(nextHref);
if (isValid) {
System.out.println("Valid Link:" + nextHref);
}
else {
System.out.println("INVALID Link:" + nextHref);
}
}
这是未经测试的代码,因此如果它不起作用,请提供更多详细信息,而不仅仅是说“它不起作用”,如果可能,请提供输出和任何堆栈跟踪/错误消息。干杯
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)