当前位置: 首页 > 知识库问答 >
问题:

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

宋子辰
2023-03-14
driver.findElement(By.id("loginUsername")).sendKeys(username);
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;
    }

}

代码错误

行,我在控制台中得到如下错误:无法找到元素:{“method”:“id”,“selector”:“loginusername”}命令持续时间或超时:262毫秒

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");
    }

共有1个答案

弓胜泫
2023-03-14

基本上,您要做的是检查浏览器发送的请求的HTTP响应代码。如果代码为200,则希望代码继续执行。如果不是,那么您希望它跳过它后面的代码。

selenium还没有实现检查响应代码的方法。您可以检查此链接以查看有关此问题的详细信息。

目前,您所能做的就是使用HTTPurlConnection发送一个链接请求,然后检查响应状态代码。

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的异常类,如下所示:

linkdoesNotexistException.java

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

然后添加这个函数,在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();
    }
}
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 WebDrive时,出现错误。我的平台是mac osx。这是我的异常日志。 我不知道为什么会这样。我的Firefox路径是默认路径。谢谢您的帮助!! 问题答案: WebDriver使用端口7054(“锁定端口”)作为互斥体,以确保我们不会同时启动两个Firefox实例。您创建的每个新实例将在启动浏览器之前等待互斥体,然后在浏览器打开后立即释放互斥体。 因

  • 无法使用由try和catch块包围的@controlleradvice和@afterthollow when方法。 我可以一步一步解释 }

  • 我目前正在尝试为spring boot实现一个自定义的错误处理程序,我已经用以下方法实现了它: 不知为什么这不起作用,并且异常仍然被抛给客户端,是否有某种方法捕获方法抛出的异常并忽略它。

  • 问题内容: 我如何在seleniumwebdriver 3.0 beta版本中使用geckodriver。当我实例化Firefox时: 我得到错误: 线程“主”中的异常java.lang.IllegalStateException:驱动程序可执行文件的路径必须由webdriver.gecko.driver系统属性设置;否则,必须执行以下操作:有关更多信息,请参见 https://github.co

  • 我将我的jms队列更改为JMS1。然而,当我执行代码时,我得到一个异常。 我的期望是,每当我得到异常时,我的bean类都应该被调用,但事实并非如此。 runtimeCamelException:org.apache.camel.FailedToCreateRouteException:在以下位置创建路由route1失败:>>>到[jms1:queue:finalqSource]<<<在route:

  • 我正在使用C#在selenium web驱动程序中为Chrome浏览器编写一个自动化脚本。我陷入了一个场景:多个选项卡在同一浏览器中打开,我需要导航到浏览器的第一个选项卡,并需要在“身份验证”对话框中重新输入登录凭据。 授权窗口截图如下: 我无法导航到第一个选项卡,也无法传递用户名 执行上述代码后,将出现以下错误: WebDriver等待有一些无效的参数。参数2:不能从int转换为System.时