Gmail登录自动化代码停留在电子邮件字段

时间:2017-09-16 19:35:01

标签: java selenium-webdriver

我正在尝试自动化gmail登录页面。 以下步骤将实现自动化: 步骤1.转到Google.com 第2步。搜索Gmail 第3步。单击Gmail 步骤4.验证您是否在Gmail站点上 步骤5.输入用户名 步骤6.单击下一步 步骤7.输入密码 步骤8.单击“登录” 步骤9.确认您获得新页面 步骤10.单击“撰写”按钮

但代码卡在电子邮件字段上。光标在电子邮件字段上一直闪烁。

以下是代码:

package com.google.mail;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class OpenGmail {

    public static void main(String[] args) {

        WebDriver driver = new InternetExplorerDriver();
        System.setProperty("webdriver.ie.driver", "C:\\Users\\Chandra\\Desktop\\SELENIUM\\IEDriver\\IEDriverServer.exe");
        driver.get("www.google.com");
        driver.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[1]/a")).click();
        driver.findElement(By.xpath("/html/body/nav/div/a[2]")).click();
        driver.findElement(By.xpath("//*[@id='initialView']/div[1]"));
        System.out.println(driver.findElement(By.id("headingText")));
        System.out.println(driver.findElement(By.id("headingSubtext")));
        driver.findElement(By.id("identifierId")).sendKeys("xxxxxkmr51");
        driver.findElement(By.className("RveJvd snByac")).click();
        driver.findElement(By.className("whsOnd zHQkBf")).sendKeys("xxxxxxxxxxxxxx");
        driver.findElement(By.className("RveJvd snByac")).click();
        System.out.println(driver.getTitle());
        driver.findElement(By.xpath("//*[@id=':j3']/div/div")).click();
       }
}

这是错误代码:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with xpath == //*[@id='initialView']/div[2]
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.5.3', revision: 'a88d25fe6b', time: '2017-08-29T12:54:15.039Z'
System info: host: 'CXxXXXX-PC', ip: '192.168.1.10', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_144'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{acceptInsecureCerts=false, browserVersion=11, se:ieOptions={nativeEvents=true, browserAttachTimeout=0, ie.ensureCleanSession=false, elementScrollBehavior=0, enablePersistentHover=true, ie.browserCommandLineSwitches=, ie.forceCreateProcessApi=false, requireWindowFocus=false, initialBrowserUrl=http://localhost:10057/, ignoreZoomSetting=false, ie.fileUploadDialogTimeout=3000, ignoreProtectedModeSettings=false}, browserName=internet explorer, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss, javascriptEnabled=true, platformName=XP, setWindowRect=true, platform=XP}]
Session ID: 99e8cbc9-b603-49b9-8cd2-de4f4a8da7f5
*** Element info: {Using=xpath, value=//*[@id='initialView']/div[2]}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:185)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:120)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:646)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:416)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:518)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:408)
    at com.google.mail.OpenGmail.main(OpenGmail.java:16)

enter image description here

6 个答案:

答案 0 :(得分:2)

这应该对你有用

您可以直接从here转到登录页面 这将使它更快并避免不必要的步骤

driver.findElement(By.id("identifierId")).sendKeys("xxxxxxxx");
driver.findElement(By.id("identifierNext")).click();

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.name("password"))); 
driver.findElement(By.name("password")).sendKeys("xxxxxxxx");
driver.findElement(By.id("passwordNext")).click();

答案 1 :(得分:2)

根据错误代码,您的测试在此步骤失败:

driver.findElement(By.xpath("//*[@id='initialView']/div[1]")); 

请删除它我认为你不需要它。其他应该工作正常。

答案 2 :(得分:1)

1-我建议你应该使用Firefox。因此,在FF中有一些用于测试开发的附加组件。例如" selenium ide"。它会记录每个步骤,然后您可以导出到您的代码。搜索它。

2 - 其他附加组件是" Selenium Page Object Generator"你可以找到所有元素xpath,css,classname。所以,你不要误认为任何定位器。搜索它!

3-你的代码在main方法中的第6行。你想要什么? " driver.findElement(By.xpath(" // * [@ id中=' initialView'] / DIV [1]&#34));"没有任何动作,如点击,发送密钥或其他任何操作。你可以这个代码。



public class GmailTest {
    private WebDriver driver;
    private String baseUrl;
    private boolean acceptNextAlert = true;
    private StringBuffer verificationErrors = new StringBuffer();

    @BeforeClass(alwaysRun = true)
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = "https://www.google.com.tr/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void testGmailscript() throws Exception {
        driver.get(baseUrl);
        driver.findElement(By.id("lst-ib")).clear();
        driver.findElement(By.id("lst-ib")).sendKeys("gmail");
        driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
        Thread.sleep(600);
        driver.findElement(By.xpath("//div[@id='rso']/div/div/div/div/div/h3/a")).click();
        driver.findElement(By.cssSelector("#identifierId")).clear();
        driver.findElement(By.cssSelector("#identifierId")).sendKeys("yourmail@gmail.com");
        driver.findElement(By.xpath(".//*[@id='identifierNext']/div[2]")).click();
        Thread.sleep(600);
        driver.findElement(By.xpath(".//*[@id='password']/div[1]/div/div[1]/input")).clear();
        driver.findElement(By.xpath(".//*[@id='password']/div[1]/div/div[1]/input")).sendKeys("password");
        driver.findElement(By.xpath(".//*[@id='passwordNext']/div[2]")).click();
        Thread.sleep(600);
        //control for gmail page is open or not. I used "write e-mail" element for control.
        Assert.assertTrue(driver.findElement(By.xpath("//div[@id=':io']/div/div")).isEnabled(),"Page is not open");
        System.out.println("Page is open");
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    private boolean isAlertPresent() {
        try {
            driver.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    private String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }
}




答案 3 :(得分:0)

使用此:

driver.get("https://accounts.google.com/")
driver.findElement(By.id("identifierId")).sendKeys("xxxxx");
driver.findElement(By.xpath(".//*[@id='identifierNext']")).click();

WebDriverWait waitforPwd= new WebDriverWait(driver, 20);
waitforPwd.until(ExpectedConditions.presenceOfElementLocated(By.id("password")); 
driver.findElement(By.id("password")).sendKeys("xxxxx");
driver.findElement(By.xpath(".//*[@id='passwordNext']")).click();

答案 4 :(得分:0)

Hi below code should work for you :


package com.google.mail;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Mytestclass {

    public static void main(String[] args) throws InterruptedException {

        WebDriver driver;
        WebDriver driver = new InternetExplorerDriver();
        System.setProperty("webdriver.ie.driver","C:\\Users\\Chandra\\Desktop\\SELENIUM\\IEDriver\\IEDriverServer.exe");


        driver.get("https://https://accounts.google.com/signin/v2/identifier?");
        driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("xxxxxxxxxxxxxxx@gmail.com");
        driver.findElement(By.xpath("//span[.='Next']")).click();
        Thread.sleep(2000);

        driver.findElement(By.xpath("//*[@id='password']/div[1]/div/div[1]/input")).sendKeys("xxxxxxxx");
        driver.findElement(By.xpath("//span[.='Next']")).click();
        Thread.sleep(4000);

        System.out.println(driver.getTitle());

       }
}

答案 5 :(得分:0)

此gmail登录脚本适用于chrome selenium ide

{
  "CreationDate": "2017-9-21",
  "Commands": [
    {
      "Command": "open",
      "Target": "https://accounts.google.com/signin/v2/identifier?flowName=GlifWebSignIn&flowEntry=ServiceLogin",
      "Value": ""
    },
    {
      "Command": "click",
      "Target": "id=identifierId",
      "Value": ""
    },
    {
      "Command": "type",
      "Target": "id=identifierId",
      "Value": "test@test.com"
    },
    {
      "Command": "click",
      "Target": "css=span.RveJvd.snByac",
      "Value": ""
    },
    {
      "Command": "pause",
      "Target": "3000",
      "Value": ""
    },
    {
      "Command": "type",
      "Target": "name=password",
      "Value": "fakepwd!"
    },
    {
      "Command": "click",
      "Target": "css=content.CwaK9",
      "Value": ""
    }
  ]
}