如何使用 Selenium WebDriver 检查 URL 中是否存在 404?
我们可以使用 Selenium WebDriver 检查 URL 中是否存在 404。404 检查实际上是要验证页面中是否存在损坏的链接。点击这样的链接时,我们不会被导向正确的页面。
损坏的链接可能由于以下原因而发生 −
目标页面不再可用。
URL 的某些部分已被修改。
页面上指定的 URL 不正确。
防火墙或地理位置限制。
URL 可能包含以下状态代码 −
5XX − 表示服务器出现问题。
4XX − 表示无法确定资源。
3XX − 表示重定向。
2XX − 表示条件正确。
因此,我们看到,只有使用 2XX 状态代码,我们才能获得正确的 URL。对于页面上的所有链接,我们将发送一个 HTTP 请求并分析它的响应代码。
示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
public class BrokenURL{
public static void main(String[] args) throws
InterruptedException{
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
// wait of 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.google.com/");
//get list of elements with anchor tag
List<WebElement> l = driver.findElements(By.tagName("a"));
//iterate links
for(int j=0; j<l.size(); j++) {
WebElement e = l.get(i);
//get URL of links with getAttribute()
String u = e.getAttribute("href");
// to catch MalFormedURLException
try{
//object of URL class
URL link = new URL(u);
// establish connection URL object
HttpURLConnection c = (HttpURLConnection)link.openConnection();
//have timeout
c.setConnectTimeout(1000);
// connection began
c.connect();
//getResponseCode() to obtain response code
if(c.getResponseCode()== 200) {
System.out.println(u+" − "+ c.getResponseMessage());
}
if(c.getResponseCode()== 404) {
System.out.println(u+" − "+c.getResponseMessage());
}
}
catch (Exception ex) {
}
}
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP