gpt4 book ai didi

java - 使用 selenium webdriver 的 Amazon 登录和注销场景

转载 作者:行者123 更新时间:2023-12-02 12:00:27 24 4
gpt4 key购买 nike

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

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“捕获”元素。

    关于java - 使用 selenium webdriver 的 Amazon 登录和注销场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47294927/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com