且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Selenium Webdriver中使用异常处理?

更新时间:2021-06-30 22:51:45

基本上,您要做的是检查浏览器正在发送的请求的HTTP响应代码.如果代码是 200 ,那么您需要该代码以继续执行.如果不是,那么您希望它跳过其后的代码.

Basically, what you want to do is check the HTTP response code of the request that the browser is sending. If the code is 200, then you want the code to continue executing. If it is not then you want it to skip the code following it.

好吧,硒尚未实现一种用于检查响应代码的方法.您可以查看此链接以查看有关此问题的详细信息.

Well, selenium has not yet implemented a method for checking the response code yet. You can check this link to see details regarding this issue.

目前,您所要做的就是使用 HttpURLConnection ,然后检查响应状态代码.

At the moment, all you can do is send a request to link by using HttpURLConnection and then check the response status code.

方法1:

您可以在调用driver.get()方法之前尝试以下操作:

You can try something like this before calling driver.get() method:

public static boolean linkExists(String URLName){
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection conn = (HttpURLConnection) new URL(URLName).openConnection();
        conn.setRequestMethod("HEAD"); // Using HEAD since we wish to fetch only meta data
        return (conn.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        return false;
    }
}

那么您可以拥有:

if(linkExists(url)) {
    driver.get(url);
    // Continue ...
} else {
    // Do something else ...
}

方法2:否则,您可以尝试此操作.像这样创建一个名为LinkDoesNotExistException的Exception类:

METHOD 2: Otherwise you can try this. Create an Exception class named LinkDoesNotExistException like this:

LinkDoesNotExistException.java

public class LinkDoesNotExistException extends Exception {
    public LinkDoesNotExistException() {
        System.out.println("Link Does Not Exist!");
    }
}

然后在A类中添加此函数.

And then add this function, in class A.

public static void openIfLinkExists(WebDriver driver, String URLName) throws LinkDoesNotExistException {
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection conn = (HttpURLConnection) new URL(URLName).openConnection();
        conn.setRequestMethod("HEAD"); // Using HEAD since we wish to fetch only meta data
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            driver.get(URLName);
        } else {
            throw new LinkDoesNotExistException();
        }
    } catch (Exception e) {
        throw new LinkDoesNotExistException();
    }
}

现在,代替使用driver.get(url),只需在try-catch块中使用openIfLinkExists(driver, url)即可.

Now, instead of using driver.get(url) simply use openIfLinkExists(driver, url) within a try-catch block.

try {
    WebDriver driver = new FirefoxDriver();
    openLinkIfExist(driver, url);
    // Continues with execution if link exist
} catch(LinkDoesNotExistException e) {
    // Exceutes this block if the link does not exist
}