How to find specific span from th class using selenium

Question:

I want to pick only one html <span> element from a <th> class and print on terminal. I’ve tried using [1] at the end of the <span> but it didn’t work out.

I’ve tried this with selenium:

for element in driver.find_elements(By.XPATH, '//div/table/thead/tr/th/span[1]'):
    print(element.text)

The html is the following:

<thead><tr class="C($tertiaryColor) Fz(xs) Ta(end)"><th class="Ta(start) W(100px) Fw(400) Py(6px)"><span>Date</span></th><th class="Fw(400) Py(6px)"><span>Open</span></th><th class="Fw(400) Py(6px)"><span>High</span></th><th class="Fw(400) Py(6px)"><span>Low</span></th><th class="Fw(400) Py(6px)"><span>Close*</span></th><th class="Fw(400) Py(6px)"><span>Adj Close**</span></th><th class="Fw(400) Py(6px)"><span>Volume</span></th></tr></thead>

Needing more information, leave a comment.

Asked By: Rodrigo

||

Answers:

The SPAN s are decendents of the TH s. Similarly the TH s are decendents of the TR. So you can use either of the following Locator Strategies:

  • xpath:

    for element in driver.find_elements(By.XPATH, '//thead/tr//th/span'):
            print(element.text)
    
  • css-selectors:

    for element in driver.find_elements(By.XPATH, 'thead > tr th > span'):
            print(element.text)
    

Update

To identify the first <span> you can use either of the following Locator Strategies:

  • xpath:

    print(driver.find_element(By.CSS_SELECTOR, "thead > tr th:nth-child(1) > span").text)
    
  • css-selectors:

    print(driver.find_element(By.XPATH, "//thead/tr//following::th[1]/span").text)
    
Answered By: undetected Selenium