Hauptideal
Hauptideal

Reputation: 123

Selenium: Get visible text of childs of WebElement, separated by spaces

I have a WebElement with many children (think of it as individual words).

I want to get all visible text of that element.

Accessing the text of the element using element.text gets the text, however there are no spaces between the texts of the children - all strings are concatenated and it is very hard to read.

When iterating over the (sometimes hierarchical) children like this to get the text instead, also invisible/duplicate text is retrieved:

texts = [c.text for c in element.find_elements_by_tag_name("span")]

I would like to get the visible text of the element (as in element.text) in a readable format by adding spaces between each visible text found on the site/element. For example, it would be sufficient to add a space to each existing string in each child.

What would be a good way of achieving this?

Upvotes: 2

Views: 396

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

To extract the visible text of the elements you need to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

print([c.text for c in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.TAG_NAME, "span")))])

Upvotes: 0

Related Questions