Kyan Heuvel
Kyan Heuvel

Reputation: 57

In Angular website, get exact text inside <div> tag with Selenium & Python?

I would like to get exact text inside tag with selenium and python.

When I inspect the element, I can see the html below on the browser.

<div class="value ng-binding" ng-bind="currentEarning">£8.8</div> == $0

I have written the python code with selenium in order to get text as follows.

currentEaring = Ladbrokes.find_element_by_xpath('//div[@ng-bind="currentEarning"]').text

When I run this script several times, I occasionally get the result as 0 - this is not true.

Rarely I can get £8.8 - this is ture.

I guess I occasionally get 0 because of the == $0 but not sure.

How can I get the text as £8.8? - using regex? If then, how?

Upvotes: 0

Views: 1361

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193108

Here is the Answer to your Question:

One of the reason to get improper results may be due to asynchronous rendering of the HTML DOM due to presence of JavaScript and AJAX calls. As you have taken help of the ng-bind attribute only so our intended node may not be the unique/first match in the HTML DOM. Hence we will refine our xpath to be more granular & unique by adding the class attribute along with ng-bind attribute and take help of get_attribute method to get the text £8.8 as follows:

currentEaring = Ladbrokes.find_element_by_xpath('//div[@class="value ng-binding" and @ng-bind="currentEarning"]').get_attribute("innerHTML")

Let me know if this Answers your Question.

Upvotes: 1

Gaurang Shah
Gaurang Shah

Reputation: 12920

it's happening may be because, it takes some time to populate the text after page has loaded, and it seems like you are not waiting enough.

you can use explicit wait to wait until element contains certain text.

For your case, following example might work.

wait = WebDriverWait(driver, 30)
wait.until(EC.text_to_be_present_in_element((By.XPATH, "//div[@ng-bind='currentEarning']"), "£"))

Upvotes: 1

Related Questions