2016-06-21 54 views
1

网页我正在自动化:https://app.ghostinspector.com/account/create硒的Java无法从网页元素文本

场景:我点击注册页面上,并输入详细信息,然后点击注册按钮,现在如果用户通过一个相同的电子邮件处理消息“电子邮件地址已被使用”。显示在网站上,所以我想要做的是找到文本消息清除它并在运行时输入另一个电子邮件地址。

现在的问题是错误消息文本不会被selenium的gettext方法获取。

下面是代码:

WebElement email_in_use = driver.findElement(
    By.xpath("/html/body/div[1]/div/div/div[2]/form/div/div[1]")); 
    String message = email_in_use.getText();  
    System.out.println(message); 

让我知道什么是这里的问题。

+0

尝试使用更好的XPath表达式,而不是工具自动生成XPath表达式。检查https://www.w3schools.com/xml/xpath_intro.asp –

+0

@AmrLotfy感谢您的建议,但这个问题放了一年,如果你没有错过发布日期:)是一个初学者在这时间。 –

回答

0

尽量usinfg这个以清除文本框

driver.switchTo().alert().getText(); 
+0

那不是问题。我无法获得“电子邮件地址已被使用”的文字。从webelement email_in_use .... –

+0

可以分享该email_in_use标记的HTML代码 – SaiPawan

+0

当然可以。

E-mail address is already in use.

0

您正在使用的getAttribute(“值”)得到的div元素的文本。尝试使用email_in_use.getText()。

+0

yup Sudharshan最初尝试过gettext()方法,但它并不奏效。 –

+0

它对我来说工作正常。尝试添加Thread.sleep(2000)后单击创建帐户按钮并从div中获取文本。 –

+0

@SudharsanSelvarj'Thread.sleep'不是一个更好的解决方案来实现它,你需要用'ExpectedCondition'实现'WebDriverWait' ... :) –

0

这里需要实现WebDriverWaitgetText()因为error元素没有任何文本已经存在那里,它填充文本时出现像E-mail地址的任何错误已在使用。

所以,你需要等到error元素有一些文字像如下: -

WebDriverWait wait = new WebDriverWait(driver, 100); 

String message = wait.until(new ExpectedCondition<String>() { 
        public String apply(WebDriver d) { 
         WebElement el = d.findElement(By.xpath("/html/body/div[1]/div/div/div[2]/form/div/div[1]")); 
         if(el.getText().length() != 0) { 
          return el.getText(); 
         } 
        } 
       }); 

System.out.println(message); 

注意: - 当你的xpath是位置是依赖于元素位置,它可能会失败,如果在行动中会有一些元素添加,我建议,你可以使用这个xpathBy.xpath("//div[@ng-show='errors']")

您也可以使用像如下: -

wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@ng-show='errors']"), "E-mail address is already in use")); 
WebElement email_in_use = driver.findElement(By.xpath("//div[@ng-show='errors']")); 
String message = email_in_use.getText(); 

希望它会工作.... :)

1

你只需要一个短暂的观望等待,直到包含错误信息的DIV出现。下面的代码正在为我工​​作。

WebDriver driver = new FirefoxDriver(); 
driver.get("https://app.ghostinspector.com/account/create"); 
driver.findElement(By.id("input-firstName")).sendKeys("Johnny"); 
driver.findElement(By.id("input-lastName")).sendKeys("Smith"); 
driver.findElement(By.id("input-email")).sendKeys("[email protected]"); 
driver.findElement(By.id("input-password")).sendKeys("abc123"); 
driver.findElement(By.id("input-terms")).click(); 
driver.findElement(By.id("btn-create")).click(); 
WebDriverWait wait = new WebDriverWait(driver, 10); 
WebElement e = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[ng-show='errors']"))); 
System.out.println(e.getText()); 
0

您试过element.getAttribute('value')

src