1

I have a table in which each row has a xpath and within each row a column is embedded. There is a tag in row's xpath that changes text based on what you choose on that page.

<div class='xyz'>
  <span> some text </span>
</div>

I am doing //div[@class='xyz']/span.text()

However, I am not able to get the text from here.

I am using python with VSCode.

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
  • This is not a valid syntax `//div[@class='xyz']/span.text()`. You need to use `//div[@class='xyz']/span/text()` or just use this `driver.find_element_by_xpath("//div[@class='xyz']/span").text` – CodeIt Aug 17 '19 at 02:52

3 Answers3

2

The syntax to get the text from span tag using xpath is incorrect.

This is the proper xpath,

//div[@class='xyz']/span/text()

Or you can use .text with web driver find_element_by_xpath to extract text.

span_text = driver.find_element_by_xpath("//div[@class='xyz']/span").text

If /span is the only child element of //div[@class='xyz'] then you can use this path instead of the one above driver.find_element_by_xpath("//div[@class='xyz']").text

You can read about how to use xpath with selenium webdriver here.

CodeIt
  • 2,882
  • 3
  • 19
  • 33
1

Try using xpath the bellow :

get_text = driver.find_element_by_xpath('//*[@class="xyz"]').text
print get_text
frianH
  • 5,901
  • 6
  • 13
  • 36
0

To extract the text some text from the desired element you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.xyz>span"))).get_attribute("innerHTML"))
    
  • Using XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='xyz']/span"))).get_attribute("innerHTML"))
    
  • 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
    
DebanjanB
  • 118,661
  • 30
  • 168
  • 217