'Unable to print the text using Python Selenium?
So I want to print out "ou" from this HTML via XPath.
<div class="syllable">ou</div>
This is my code:
elem = driver.find_elements_by_xpath('*my xpath*')
for my_elem in elem:
print(my_elem.text)
I used .text
in this code but it just prints out nothing when it runs. It should be printing ou
but it just prints nothing at all. If someone could please tell me what I am doing wrong that would be great.
Solution 1:[1]
To print the text ou
you can use either of the following Locator Strategies:
Using
css_selector
andget_attribute("innerHTML")
:print(driver.find_element_by_css_selector("div.syllable").get_attribute("innerHTML"))
Using
xpath
and text attribute:print(driver.find_element_by_xpath("//div[@class='syllable']").text)
Ideally you need to induce WebDriverWait for the visibility_of_element_located()
and you can use either of the following Locator Strategies:
Using
CSS_SELECTOR
and text attribute:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.syllable"))).text)
Using
XPATH
andget_attribute()
:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='syllable']"))).get_attribute("innerHTML"))
Console Output:
ou
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python
References
Link to useful documentation:
get_attribute()
methodGets the given attribute or property of the element.
text
attribute returnsThe text of the element.
- Difference between text and innerHTML using Selenium
Solution 2:[2]
if you are unable to print the text using .text then use .get_attribute("innerHTML") this will defiantly print out the text.
eg. your code should look like this
elem = driver.find_elements_by_xpath('*my xpath*').get_attribute("innerHTML")
for my_elem in elem:
print(my_elem)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | undetected Selenium |
Solution 2 | softcode |