Cannot get text of element with Selenium
Question:
I have the DOM element below:
<span class="styles__Content-rlm06o-1 ixoRjG">20.00000000</span>
that I am trying to get the 20.00000000
value from with:
text = driver.find_elements_by_xpath("//*[@class='styles__Content-rlm06o-1 ixoRjG']")[0].text
...
number = float(text)
But Python returns back could not convert string to float: ''
meaning that the 20.00000000
is not being recognized as text. This code has worked on other websites, so maybe this is a website specific thing? Or is there something I’m overlooking?
Answers:
You can try to get the text of the first element with this XPath expression:
el_text = driver.find_element_by_xpath("//span[contains(@class, 'styles__Content-rlm06o-1 ixoRjG')][1]").text
Also, you can use CSS selectors with way:
el_text = driver.find_element_by_css_selector(".styles__Content-rlm06o-1.ixoRjG:nth-of-type(1)").text
If the text is still empty, make sure you are waiting for the element to become visible and that this element is not inside an iframe.
You are probably getting a different element from that list. I suggest a similar approach as proposed by vitaliis, but instead of looking by class, look by text.
text = driver.find_element_by_xpath("//span[contains(text(), '20')]").text
number = float(text)
print(number)
I have the DOM element below:
<span class="styles__Content-rlm06o-1 ixoRjG">20.00000000</span>
that I am trying to get the 20.00000000
value from with:
text = driver.find_elements_by_xpath("//*[@class='styles__Content-rlm06o-1 ixoRjG']")[0].text
...
number = float(text)
But Python returns back could not convert string to float: ''
meaning that the 20.00000000
is not being recognized as text. This code has worked on other websites, so maybe this is a website specific thing? Or is there something I’m overlooking?
You can try to get the text of the first element with this XPath expression:
el_text = driver.find_element_by_xpath("//span[contains(@class, 'styles__Content-rlm06o-1 ixoRjG')][1]").text
Also, you can use CSS selectors with way:
el_text = driver.find_element_by_css_selector(".styles__Content-rlm06o-1.ixoRjG:nth-of-type(1)").text
If the text is still empty, make sure you are waiting for the element to become visible and that this element is not inside an iframe.
You are probably getting a different element from that list. I suggest a similar approach as proposed by vitaliis, but instead of looking by class, look by text.
text = driver.find_element_by_xpath("//span[contains(text(), '20')]").text
number = float(text)
print(number)