简体   繁体   中英

How to locate the element using XPath Selenium and Python

I need to get the number "3" from this HTML with python selenium

<div class="number">3</div>

This is the XPATH:

//*[@id="roulette-recent"]/div/div[1]/div[1]/div/div

I tried something like

number = navegador.find_element_by_xpath('//*[@id="rouletterecent"]/div/div[1]/div[1]/div/div').get_attribute('class')

I think you're looking for:

number = navegador.find_element_by_xpath('//*[@id="rouletterecent"]/div/div[1]/div[1]/div/div').text

To print the text 3 you can use either of the following Locator Strategies :

  • Using css_selector and get_attribute("innerHTML") :

     print(navegador.find_element(By.CSS_SELECTOR, "#roulette-recent div.number").get_attribute("innerHTML"))
  • Using xpath and text attribute:

     print(navegador.find_element(By.XPATH, "//*[@id="roulette-recent"]//div[@class='number' and text()]").text)

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies :

  • Using CSS_SELECTOR and text attribute:

     print(WebDriverWait(navegador, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#roulette-recent div.number"))).text)
  • Using XPATH and get_attribute("innerHTML") :

     print(WebDriverWait(navegador, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@id="roulette-recent"]//div[@class='number' and text()]"))).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

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python


References

Link to useful documentation:

If this xpath

//*[@id="rouletterecent"]/div/div[1]/div[1]/div/div

represent the node:

<div class="number">3</div>

and you want to extract the text from it, you should use either:

number = navegador.find_element_by_xpath('//*[@id="rouletterecent"]/div/div[1]/div[1]/div/div').get_attribute('innerText')
print(number)

or

number = navegador.find_element_by_xpath('//*[@id="rouletterecent"]/div/div[1]/div[1]/div/div').text
print(number)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM