I need to get the number "3" from this HTML with python selenium
<div >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')
CodePudding user response:
I think you're looking for:
number = navegador.find_element_by_xpath('//*[@id="rouletterecent"]/div/div[1]/div[1]/div/div').text
CodePudding user response:
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:
get_attribute()methodGets the given attribute or property of the element.textattribute returnsThe text of the element.- Difference between text and innerHTML using Selenium
CodePudding user response:
If this xpath
//*[@id="rouletterecent"]/div/div[1]/div[1]/div/div
represent the node:
<div >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)
