Home > Back-end >  Can't get Text with Find Element by xpath with Selenium
Can't get Text with Find Element by xpath with Selenium

Time:11-05

I am trying to get all the text from the element 'show-more-less-html__markup' from the example below with selenium and Python:

enter image description here

This is my try :

description = browser.find_element_by_xpath("//div[@class='show-more-less-html__markup']").text

CodePudding user response:

This is not Python

browser.findElement(By.className("description__text description__text--rich")).getText();

It's Java.
You are mixing things...

CodePudding user response:

Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

xpath that you should check :

//div[@class='show-more-less-html__markup']

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

If we have 1/1 matching node, Please make sure that :

  1. This div is not under an iframe.
  2. This div is not under a shadow-root.
  3. You should not be on new tab/windows launched by selenium.

Once we are sure that we have unique entry and other criteria matches as well, we can try to extract text in the following way :

Code trial 1 :

try:
    msg = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='show-more-less-html__markup']"))).text
    print(msg)
except:
    pass

Code trial 2 :

try:
    msg = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='show-more-less-html__markup']"))).get_atrribute('innerHTML')
    print(msg)
except:
    pass

Code trial 3 :

try:
    msg = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='show-more-less-html__markup']"))).get_attribute('innerText')
    print(msg)
except:
    pass

Imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
  • Related