Malekulo
Malekulo

Reputation: 13

How to get text from element using xpath

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 class="checkout-list">
  <div class="notification notification__inform " id="inform-not-product">
   <div class="message">
    <div class="text">
     "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(

Upvotes: 0

Views: 2218

Answers (1)

KunduK
KunduK

Reputation: 33384

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[@class="text"]')))
    information_message = browser.find_element(By.XPATH, '//div[@id="inform-not-product"]//div[@class="text"]').text

Upvotes: 1

Related Questions