Home > Blockchain >  How to get text from element using xpath
How to get text from element using xpath

Time:02-27

I want to write an assert to compare the expected text with the actual one. To do this, I need to pull out the text. Here is the code:

<div >
  <div  id="inform-not-product">
   <div >
    <div >
     "some test text"
    </div>
   </div>
  </div>
</div>

Here is my code:

WebDriverWait(browser, 5).until(
        EC.presence_of_element_located((By.XPATH, '//div[contains(@id, "inform-not-product")]//div[contains(@class, "text")]')))
information_message = browser.find_element(By.XPATH, '//div[contains(@id, "inform-not-product")]//div[contains(@class, "text")]').text()

I get an error:

Traceback (most recent call last): File "/Users/user/PycharmProjects/automation/tests/sales/1.py", line 130, in information_message = browser.find_element(By.XPATH, '//div[contains(@id, "inform-not-product")]//div[contains(@class, "text")]').text() TypeError: 'str' object is not callable

Also i tried to do the same with XPATH

WebDriverWait(browser, 5).until(
        EC.presence_of_element_located((By.XPATH, '//div[contains(@id, "inform-not-product")]//div[contains(@class, "text")]/text()[1]')))
information_message = browser.find_element(By.XPATH, '//div[contains(@id, "inform-not-product")]//div[contains(@class, "text")]/text()[1]').text()

and i get another error:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//div[contains(@id, "inform-not-product")]//div[contains(@class, "text")]/text()[1]" is: [object Text]. It should be an element.

Pls help(

CodePudding user response:

text() is not exist in selenium. you need to use only text

Use visibility_of_element_located() instead of presence_of_element_located()

You can ignore contains since it doesn't contains dynamic string.

WebDriverWait(browser, 5).until(
            EC.visibility_of_element_located((By.XPATH, '//div[@id="inform-not-product"]//div[@]')))
    information_message = browser.find_element(By.XPATH, '//div[@id="inform-not-product"]//div[@]').text
  • Related