Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

java - getText() method of selenium chrome driver sometimes returns an empty string

I have a curious case where the selenium chrome driver getText() method (java) returns an empty string for some elements, even though it returns a non-empty string for other elements with the same xpath. Here is a bit of the page.

<div __gwt_cell="cell-gwt-uid-223" style="outline-style:none;">
<div>Text_1</div>
<div>Text_2</div>
<div>Text_3</div>
<div>Text_4</div>
<div>Text_5</div>
<div>Text_6</div>
</div>

for each of the inner tags, I can get valid return values for getTagName(), getLocation(), isEnabled(), and isDisplayed(). However, getText() returns an empty string for some of the divs.

Further, I notice that if I use the mac chrome driver, it is consistently the ‘Text_5’ for which getText() returns an empty string. If I use the windows chrome driver, it is , it is consistently the ‘Text_2’ for which getText() returns an empty string. If I use the firefox driver, getText() returns the expected text from all the divs.

Has anyone else had this difficulty?

In my code, I use something like this…

ArrayList<WebElement> list = (ArrayList<WebElement>) driver.findElements(By.xpath(“my xPath here”));
for (WebElement e: list) System.out.println(e.getText());

As suggested below, here is the actual xPath I am using. The page snippet above deals with the last two divs.

//*[@class='gwt-DialogBox']//tr[contains(@class,'data-grid-table-row')]//td[contains(@class,'lms-assignment-selection-wizard-cell')]/div/div
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update: The textContent attribute is a better option and supported across the majority of browsers. The differences are explained in detail at this blog post: innerText vs. textContent

As an alternative, the innerText attribute will return the text content of an element which exists in the DOM.

element.getAttribute("innerText")

The isDisplayed() method can sometimes trip over when the element is not really hidden but outside the viewport; getText() returns an empty string for such an element.

You can also bring the element into the viewport by scrolling to it using javascript, as follows:

((JavaScriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);

and then getText() should return the correct value.

Details on the isDisplayed() method can be found in this SO question:

How does Selenium WebDriver's isDisplayed() method work


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...