I want to pick only one html span element from a th class to print on terminal. I've tried using [1] at the end of the span but it didnt work out.
I have 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 ><th ><span>Date</span></th><th ><span>Open</span></th><th ><span>High</span></th><th ><span>Low</span></th><th ><span>Close*</span></th><th ><span>Adj Close**</span></th><th ><span>Volume</span></th></tr></thead>
Needing more information, leave a comment.
CodePudding user response:
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)
