如何使用Java在Selenium2(Webdriver)中键入Gmail正文文本

我尝试自动从Gmail发送电子邮件(https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/&scc=1&ltmpl=default&ltmplcache=2)使用Selenium WebDriver和Java。 首先,我尝试使用Selenium IDE记录测试。 IDE无法记录电子邮件正文。 我尝试通过以下方式键入正文,但不幸的是它失败了。

driver.findElement(By.xpath(“// textarea [@ name =’body’]”))。sendKeys(“body text”);

错误是:FAILED:testSendingEmail org.openqa.selenium.ElementNotVisibleException:元素当前不可见,因此可能无法与命令持续时间或超时交互:30.02秒

有人可以帮帮我吗?

是..您无法使用Selenium IDE记录电子邮件正文

在项目中包含以下方法并调用该方法发送电子邮件。(无需登录gmail)

import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public void SendEmail() { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message Transport.send(message); //System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } } 

您还可以使用附件发送邮件

有关更多信息,请参阅此链接 。

当使用类时它会抛出并且找不到错误元素使用表索引更好。

  WebElement frame1 = driver.findElement(By.xpath("//iframe[@tabindex='1']")); driver.switchTo().frame(frame1); WebElement editable = driver.switchTo().activeElement(); String mailBody = "Hi," + '\n' + "Gmail Body"; editable.sendKeys(mailBody); driver.switchTo().defaultContent(); 

以下是用于输入gmail正文的HTML代码:

  

我在WebDriver中编写了以下java代码来键入gmail body,它运行良好。 (我很开心)

 WebDriver driver = new FirefoxDriver(); WebElement frame1 = driver.findElement(By.xpath("//iframe[@class='Am Al editable']")); driver.switchTo().frame(frame1); WebElement editable = driver.switchTo().activeElement(); String mailBody = "Hi," + '\n' + "I'm Ripon from Dhaka, Bangladesh."; editable.sendKeys(mailBody); driver.switchTo().defaultContent(); 

尝试下面的代码写入正文区域

 driver.findElement(By.cssSelector("body[class='editable LW-avf']")).clear(); driver.findElement(By.cssSelector("body[class='editable LW-avf']")).sendKeys("body text"); 

WebDriver driver = new FirefoxDriver();

WebElement text = driver.findElement(By.className(“LW-avf”));

text.click(); text.sendKeys( “你好”);

请尝试使用上面的代码。