Java 使用SeleniumWebDriver的Amazon登录和注销场景

Java 使用SeleniumWebDriver的Amazon登录和注销场景,java,selenium,webdriver,Java,Selenium,Webdriver,我是硒的新手。 我正在尝试自动化亚马逊登录和注销。 我面临两个问题 1.在登录页面中,当我第一次尝试登录时,用户名后面会出现“继续”按钮。 但后来当我第二次尝试登录时,它并没有出现。 如何处理这个问题。 以下是我迄今为止编写的代码: public void logindetails() { Datafile d=new Datafile("C:\\Users\\kirruPC\\selenium divers\\Data.xlsx",0); String un

我是硒的新手。 我正在尝试自动化亚马逊登录和注销。 我面临两个问题

1.在登录页面中,当我第一次尝试登录时,用户名后面会出现“继续”按钮。 但后来当我第二次尝试登录时,它并没有出现。 如何处理这个问题。 以下是我迄今为止编写的代码:

public void logindetails()
{

        Datafile d=new Datafile("C:\\Users\\kirruPC\\selenium divers\\Data.xlsx",0);

        String uname= d.username(0, 0);
        WebElement u=driver.findElement(useid);
        u.sendKeys(uname);
        u.click();



        if(driver.findElement(By.xpath(".//*[@id='continue']")).isDisplayed()==true)
        {
            driver.findElement(By.id("continue")).click();
            String psw=d.pass(0,1);
            driver.findElement(password).sendKeys(psw);
        }
        else
        {
            String psw=d.pass(0,1);
            driver.findElement(password).sendKeys(psw);
        }
}
  • 找不到注销元素
  • 以下是我编写的代码,用于移动到注销链接并单击:

         public void logout() throws Exception
         {
    
              Actions a= new Actions(driver);
              WebElement ele=driver.findElement(By.xpath(".//*[@id='nav-link-accountList']"));
              a.moveToElement(ele).build().perform();
    
    
    
              driver.findElement(By.xpath(".//*[@id='nav-al-your-account']"));
              Thread.sleep(3000);
              driver.findElement(By.xpath(".//*[@id='nav-al-your-account']/a[22]")).click();
         }
    
    请帮帮我


    提前感谢

    首先,您正在搜索的元素在页面中可能根本不存在,因此首先让我们检查该元素是否存在(如果该元素不存在,则引发异常,因此我们也为其添加一个句柄)。为此,创建如下函数:

    public bool ElementExists(By locator)
    {
        try
        {
            driver.findElement(locator); 
            //If no exception is thrown here, element exists, so return true
            return true; 
        }
        catch (NoSuchElementException ex)
        {
            return false;
        {
    }
    
    现在我们有了一个函数,可以安全地检查元素是否存在,而不会出现异常,您可以使用它来确定是否要运行处理该元素的代码。 函数
    isDisplayed()
    已返回bool,因此无需检查是否等于true

    if(ElementExists(By.xpath(...)).isDisplayed())
    {
        if(driver.findElement(By.xpath(".//*[@id='continue']")).isDisplayed())
        {
            driver.findElement(By.id("continue")).click();
        }
    }
    //The code below will run either way, so move it out of the if statement
    String psw=d.pass(0,1);
    driver.findElement(password).sendKeys(psw);
    
    至于问题的第二部分,只需搜索元素,然后按如下方式单击即可简化代码:

    driver.findElement(By.xpath(".//*[@id='nav-al-your-account']/a[22]")).click();
    

    如果愿意,请仔细检查xpath或通过ID“捕获”元素。

    发布您试图编码的链接。当我尝试登录时,我只得到一个“登录”按钮。但是,我在“密码帮助”页面上看到了“继续”。