【问题标题】:Open mails from Gmail inbox using selenium webdriver using java使用 java 使用 selenium webdriver 从 Gmail 收件箱打开邮件
【发布时间】:2016-08-14 01:26:41
【问题描述】:

我需要使用 Eclipse IDE 中的 java 使用 selenium webdriver 从 Gmail 收件箱打开邮件。有没有办法使用 xpath 做到这一点?

【问题讨论】:

  • 是的,有办法。
  • 我会说。 (为了匹配问题的质量。)你不能用 xpath 打开任何东西。 ;)
  • 在询问编码查询时,您应该发布您自己尝试过的任何内容。仅仅寻求帮助而不尝试从你身边不会帮助你得到答案。

标签: java selenium xpath selenium-webdriver incoming-mail


【解决方案1】:

理想的方法是不使用 selenium 来自动化 gmail,而是使用 Gmail API (https://developers.google.com/gmail/api/#how_do_i_find_out_more) 来验证邮件是否已成功发送。如果您不想学习如何在 API 级别检查消息,我强烈建议您使用 HTML 版本的 gmail,使用此链接作为 gmail (https://mail.google.com/mail/?ui=html) 的初始 url,使用启用 javascript 的 gmail 会变得更加困难有一个可靠的测试脚本。

【讨论】:

    【解决方案2】:

    这是我的解决方案,没有任何 thread.sleap() 等。

       driver.get("https://mail.google.com/");                                                                                                                        
    
       WebElement userElement = wait.until(ExpectedConditions.elementToBeClickable(By.id("identifierId")));                                                           
       userElement.click();                                                                                                                                           
       userElement.clear();                                                                                                                                           
       userElement.sendKeys(properties.getProperty("username"));                                                                                                      
    
       WebElement identifierNext = wait.until(ExpectedConditions.elementToBeClickable(By.id("identifierNext")));                                                      
       identifierNext.click();                                                                                                                                        
    
       WebElement passwordElement = wait.until(ExpectedConditions.elementToBeClickable(By.name("password")));                                                         
       passwordElement.click();                                                                                                                                       
       passwordElement.clear();                                                                                                                                       
       passwordElement.sendKeys(properties.getProperty("password"));                                                                                                  
    
       WebElement passwordNext = wait.until(ExpectedConditions.elementToBeClickable(By.id("passwordNext")));                                                          
       passwordNext.click();                                                                                                                                          
    
       WebElement composeElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@role='button' and (.)='Compose']")));                            
       composeElement.click();                                                                                                                                        
    
       WebElement maximizeEmailElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//td//img[2]")));                                               
       maximizeEmailElement.click();                                                                                                                                  
    
       WebElement sendToElement = wait.until(ExpectedConditions.elementToBeClickable(By.name("to")));                                                                 
       sendToElement.click();                                                                                                                                         
       sendToElement.clear();                                                                                                                                         
       sendToElement.sendKeys(String.format("%s@gmail.com", properties.getProperty("username")));                                                                     
    
       WebElement subjectElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@name = 'subjectbox']")));                                        
       subjectElement.click();                                                                                                                                        
       subjectElement.clear();                                                                                                                                        
       subjectElement.sendKeys(properties.getProperty("email.subject"));                                                                                              
    
       WebElement emailBodyElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@role = 'textbox']")));                                         
       emailBodyElement.click();                                                                                                                                      
       emailBodyElement.clear();                                                                                                                                      
       emailBodyElement.sendKeys(properties.getProperty("email.body"));                                                                                               
    
       WebElement sendMailElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[text()='Send']")));                                            
       sendMailElement.click();                                                                                                                                       
    
       wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'Message sent')]")));                                                   
       List<WebElement> inboxEmails = wait.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.xpath("//*[@class='zA zE']"))));                   
    
       for(WebElement email : inboxEmails){                                                                                                                           
           if(email.isDisplayed() && email.getText().contains("email.subject")){                                                                                                                                   
               email.click();                                                                                                                                         
    
               WebElement label = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@title,'with label Inbox')]")));                    
               WebElement subject = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h2[contains(text(),'Subject of this message')]")));          
               WebElement body = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Single line body of this message')]")));   
    
           }                                                                                                                                                          
       }       
    

    【讨论】:

    • 我似乎没有在收件箱电子邮件的社交标签中收到任何文本。
    【解决方案3】:

    我同意@sonhu 并做了同样的事情。使用 JAVAX MAIL API(不是 GMAIL API)对这个问题进行了排序。

        public GmailUtils(String username, String password, String server, EmailFolder 
            emailFolder) throws Exception {
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imaps.partialfetch", "false");
        props.put("mail.imap.ssl.enable", "true");
        props.put("mail.mime.base64.ignoreerrors", "true");
    
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imap");
        store.connect("imap.gmail.com", 993, "<your email>", "<your password>");
    
        Folder folder = store.getFolder(emailFolder.getText());
        folder.open(Folder.READ_WRITE);
    
        System.out.println("Total Messages:" + folder.getMessageCount());
        System.out.println("Unread Messages:" + folder.getUnreadMessageCount());
    
        messages = folder.getMessages();
    
        for (Message mail : messages) {
            if (!mail.isSet(Flags.Flag.SEEN)) {
    
                System.out.println("***************************************************");
                System.out.println("MESSAGE : \n");
    
                System.out.println("Subject: " + mail.getSubject());
                System.out.println("From: " + mail.getFrom()[0]);
                System.out.println("To: " + mail.getAllRecipients()[0]);
                System.out.println("Date: " + mail.getReceivedDate());
                System.out.println("Size: " + mail.getSize());
                System.out.println("Flags: " + mail.getFlags());
                System.out.println("ContentType: " + mail.getContentType());                
                System.out.println("Body: \n" + getEmailBody(mail));
                System.out.println("Has Attachments: " + hasAttachments(mail));
    
            }
        }
    }
    
    
    public boolean hasAttachments(Message email) throws Exception {
    
        // suppose 'message' is an object of type Message
        String contentType = email.getContentType();
        System.out.println(contentType);
    
        if (contentType.toLowerCase().contains("multipart/mixed")) {
            // this message must contain attachment
            Multipart multiPart = (Multipart) email.getContent();
    
            for (int i = 0; i < multiPart.getCount(); i++) {
                MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
                if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                    System.out.println("Attached filename is:" + part.getFileName());
    
                    MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
                    String fileName = mimeBodyPart.getFileName();
    
                    String destFilePath = System.getProperty("user.dir") + "\\Resources\\";
    
                    File fileToSave = new File(fileName);
                    mimeBodyPart.saveFile(destFilePath + fileToSave);
    
                    // download the pdf file in the resource folder to be read by PDFUTIL api.
    
                    PDFUtil pdfUtil = new PDFUtil();
                    String pdfContent = pdfUtil.getText(destFilePath + fileToSave);
    
                    System.out.println("******---------------********");
                    System.out.println("\n");
                    System.out.println("Started reading the pdfContent of the attachment:==");
    
    
                    System.out.println(pdfContent);
    
                    System.out.println("\n");
                    System.out.println("******---------------********");
    
                    Path fileToDeletePath = Paths.get(destFilePath + fileToSave);
                    Files.delete(fileToDeletePath);
                }
            }
    
            return true;
        }
    
        return false;
    }
    
    public String getEmailBody(Message email) throws IOException, MessagingException {
    
        String line, emailContentEncoded;
        StringBuffer bufferEmailContentEncoded = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
        while ((line = reader.readLine()) != null) {
            bufferEmailContentEncoded.append(line);
        }
    
        System.out.println("**************************************************");
    
        System.out.println(bufferEmailContentEncoded);
    
        System.out.println("**************************************************");
    
        emailContentEncoded = bufferEmailContentEncoded.toString();
    
        if (email.getContentType().toLowerCase().contains("multipart/related")) {
    
            emailContentEncoded = emailContentEncoded.substring(emailContentEncoded.indexOf("base64") + 6);
            emailContentEncoded = emailContentEncoded.substring(0, emailContentEncoded.indexOf("Content-Type") - 1);
    
            System.out.println(emailContentEncoded);
    
            String emailContentDecoded = new String(new Base64().decode(emailContentEncoded.toString().getBytes()));
            return emailContentDecoded;
        }
    
        return emailContentEncoded;
    
    }
    

    【讨论】:

      【解决方案4】:

      包包1; 导入 java.util.concurrent.TimeUnit;

      import org.openqa.selenium.By;
      

      导入 org.openqa.selenium.chrome.ChromeDriver;

      public class class1 {
          public static void main(String[] args) throws InterruptedException{
              System.setProperty("webdriver.chrome.driver","C:\\Users\\name\\Desktop\\chromedriver.exe");
              ChromeDriver driver=new ChromeDriver();
              driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
              driver.get("https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin");
              driver.findElement(By.id("identifierId")).sendKeys("****@gmail.com");
              driver.findElement(By.id("identifierNext")).click();
              driver.findElement(By.xpath("//input[@aria-label='Enter your password' and @name='password']")).sendKeys("********");
              Thread.sleep(200);
              driver.findElement(By.id("passwordNext")).click();
      
      
          }}
      

      【讨论】:

        【解决方案5】:

        您好,请在下面尝试这样代码仅检查未读邮件

        public static void main(String[] args) {
            // TODO Auto-generated method stub. 
        
        System.setProperty("webdriver.chrome.driver","D:\\eclipseProject\\StackOverFlow\\chromedriver_win32 (1)\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        
        driver.get("https://accounts.google.com/ServiceLogin?");
        
        // gmail login
        driver.findElement(By.id("Email")).sendKeys("your gmail username");
        driver.findElement(By.id("next")).click();
        driver.findElement(By.id("Passwd")).sendKeys("your gmail password");
        driver.findElement(By.id("signIn")).click();
        
        // some optional actions for reaching gmail inbox
        driver.findElement(By.xpath("//*[@title='Google apps']")).click();
        driver.findElement(By.id("gb23")).click();
        
        // now talking un-read email form inbox into a list
        List<WebElement> unreademeil = driver.findElements(By.xpath("//*[@class='zF']"));
        
        // Mailer name for which i want to check do i have an email in my inbox 
        String MyMailer = "Stack over flow";
        
        // real logic starts here
        for(int i=0;i<unreademeil.size();i++){
            if(unreademeil.get(i).isDisplayed()==true){
                // now verify if you have got mail form a specific mailer (Note Un-read mails)
                // for read mails xpath loactor will change but logic will remain same
                if(unreademeil.get(i).getText().equals(MyMailer)){
                    System.out.println("Yes we have got mail form " + MyMailer);
                    // also you can perform more actions here 
                    // like if you want to open email form the mailer
                    break;
                }else{
                    System.out.println("No mail form " + MyMailer);
                }
            }
        }
        

        }

        【讨论】:

        • 大家好,感谢大家的帮助。我试过这样并让它工作正常: List x = driver.findElements(By.xpath("//*[@class='yW']/span")); System.out.println(x.size()); for (int i = 0; i
        • 根据 selenium doc,这不是去见Worst practices的方法
        【解决方案6】:
        //open a mail from the gmail inbox.
        List<WebElement> a = driver.findElements(By.xpath("//*[@class='yW']/span"));
                    System.out.println(a.size());
                    for (int i = 0; i < a.size(); i++) {
                        System.out.println(a.get(i).getText());
                        if (a.get(i).getText().equals("Support")) //to click on a specific mail.
                            {                                           
                            a.get(i).click();
                        }
                    }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-03-02
          • 1970-01-01
          • 2011-08-17
          • 1970-01-01
          • 2015-04-07
          • 2015-10-21
          • 1970-01-01
          相关资源
          最近更新 更多