如何在Selenium Webdriver中使用异常处理? [英] How to use Exception Handling in Selenium Webdriver?

查看:133
本文介绍了如何在Selenium Webdriver中使用异常处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方案如下: 当代码 driver.get(url); 运行时,如果URL无法访问(如果服务器无法访问),则应引发服务器无法访问的异​​常,并且代码应停止执行下一行

The Scenario is as follows: When the code driver.get(url); runs, if the URL is not able to access (if server is not reachable) then it should throw an exception that server is not reachable and the code should stop executing the next line

driver.findElement(By.id("loginUsername")).sendKeys(username);

我在eclipse中运行的以下代码如下:

The following code I'm running in eclipse as follows:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class A {


    static Properties p= new Properties();
    String url=p.getProperty("url");
    private static Logger Log = Logger.getLogger(A.class.getName());

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, InterruptedException {
        WebDriver driver = new FirefoxDriver();
        A a = new A();

        Actions actions = new Actions(driver);
        DOMConfigurator.configure("src/log4j.xml");
        String url = a.readXML("logindetails","url");
        String username = a.readXML("logindetails","username");
        String password = a.readXML("logindetails","password");

        //use username for webdriver specific actions
        Log.info("Sign in to the OneReports website");
        driver.manage().window().maximize();
        driver.get(url);// In this line after opens the browser it gets the URL from my **D://NewFile.xml* file and try to open in the browser. If the Server is not reachable then it should stop here. else it takes the username and password from the same file then it will open the page in browser.
        Thread.sleep(5000);
        Log.info("Enter Username");
        driver.findElement(By.id("loginUsername")).sendKeys(username);
        Log.info("Enter Password");
        driver.findElement(By.id("loginPassword")).sendKeys(password); 
        //submit
        Log.info("Submitting login details");
        waitforElement(driver,120 , "//*[@id='submit']");
        driver.findElement(By.id("submit")).submit();
        Thread.sleep(5000);


    }

    private static void waitforElement(WebDriver driver, int i, String string) {
        // TODO Auto-generated method stub

    }

    public String readXML(String searchelement,String tag) throws SAXException, IOException, ParserConfigurationException{
        String ele = null;
        File fXmlFile = new File("D://NewFile.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName(searchelement);
        Node nNode = nList.item(0);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            ele=eElement.getElementsByTagName(tag).item(0).getTextContent();
        }
        return ele;
    }

}

我也尝试了这个try块方法.但是,仅移至

I tried this try block method as well. But it's not catching the exception just moving to the

driver.findElement(By.id("loginUsername")).sendKeys(用户名);

driver.findElement(By.id("loginUsername")).sendKeys(username);

代码错误

行,并且在控制台中出现以下错误:无法找到 元素:{方法":"id",选择器":"loginUsername"}命令持续时间 或超时:262毫秒

line and I'm getting error as follows in the console:Unable to locate element: {"method":"id","selector":"loginUsername"} Command duration or timeout: 262 milliseconds

try
    {
        driver.get(url);
    }
    catch(Exception e)
    {
        Reporter.log("network server is slow..check internet connection");
        Log.info("Unable to open the website");
        throw new Error("network server is slow..check internet connection");
    }

推荐答案

基本上,您要做的是检查浏览器正在发送的请求的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
}

这篇关于如何在Selenium Webdriver中使用异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆