简体   繁体   English

getText()在sendKeys()之后返回空字符串

[英]getText() returns empty string after sendKeys()

I have a class with the following public instance variable 我有一个带有以下公共实例变量的类

@FindBy(id="titleInput")
public WebElement titleInputBox;

Then I use page factory in the constructor to initialize it on every use 然后我在构造函数中使用页面工厂在每次使用时对其进行初始化

PageFactory.initElements(driver, this);

In my test case for this page, I use the following code to test whether the text I sent is actually getting set in the field ... 在此页面的测试用例中,我使用以下代码来测试发送的文本是否确实在字段中设置了...

subtitleInputBox.sendKeys("Test");
subtitleInputBox.getText();

and I get empty string 我得到空字符串

any idea why this happens ... I think it works fine if driver.findElement() is used directly without @FindBy and PageFactory 任何想法为什么会发生...我认为如果在没有@FindByPageFactory情况下直接使用driver.findElement()PageFactory

To get the text out of an input box like text or textarea you need to use the getAttribute("value") method. 要从诸如文本或textarea之类的输入框中获取文本,您需要使用getAttribute("value")方法。 getText() works for tags like div, span etc etc. getText()适用于div,span等标签。

subtitleInputBox.getAttribute("value");

Actually WebElement.getText() returns the visible (ie not hidden by CSS) innerText of this element , including sub-elements, without any leading or trailing whitespace while you need input box element value attribute text. 实际上,当您需要输入框元素值属性文本时, WebElement.getText()返回此元素 (包括子元素WebElement.getText()的可见(即未被CSS隐藏) innerText ,而没有任何前导或尾随空格。

FYI input box element stores the text which you are trying to set using WebElement.sendKeys() into their attribute name value instead of inner text. FYI输入框元素将您尝试使用WebElement.sendKeys()设置的文本存储到其属性名称value而不是内部文本中。

So you should try using WebElement.getAttribute() which to be used to get the value of a the given attribute of the element. 因此,您应该尝试使用WebElement.getAttribute()来获取元素给定属性的值。

Here you need to implement WebDriverWait also to determine whether element value has been successfully set or not using ExpectedConditions.textToBePresentInElementValue as below :- 在这里,您还需要实现WebDriverWait来确定元素值是否已经使用ExpectedConditions.textToBePresentInElementValue成功设置,如下所示:

subtitleInputBox.sendKeys("Test");

//Now wait until value has been set into element 
new WebDriverWait(driver, 10).until(ExpectedConditions.textToBePresentInElementValue(subtitleInputBox, "Test"));

//Now get the element value
subtitleInputBox.getAttribute("value");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM