Home > Back-end >  Selenium - How to identify li item based on value
Selenium - How to identify li item based on value

Time:02-25

I have the following list in a webpage that I am trying to scrape:

<div  style="height: 54px; width: 100%;">
<ul >
<li >Jules Salles-Wagner (FRENCH, 1814–1898)</li>
<li >Peter Nadin (BRITISH, 1954)</li>
<li >Uri Aran (ISRAELI, 1977)</li>
</ul>
</div>

I want to select the item that contains the text Uri Aran. How can I do that through Selenium? There are other lists with different class name in the same website as well.

CodePudding user response:

driver.find_element(By.XPATH,"//li[@class='rcbItem' and contains(text(),'Uri Aran')]").click()

You'd want to get the one that contains the text of Uri Aran.

CodePudding user response:

To locate the element with text Uri Aran 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 nth-child():

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.rcbScroll.rcbWidth > ul.rcbList li:nth-child(3)")))
    
  • Using CSS_SELECTOR and nth-of-type():

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.rcbScroll.rcbWidth > ul.rcbList li:nth-of-type(3)")))
    
  • Using CSS_SELECTOR and last-child:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.rcbScroll.rcbWidth > ul.rcbList li:last-child")))
    
  • Using CSS_SELECTOR and last-of-type:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.rcbScroll.rcbWidth > ul.rcbList li:last-of-type")))
    
  • Using XPATH and index:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='rcbScroll rcbWidth']/ul[@class='rcbList']//following::li[3]")))
    
  • Using XPATH and last():

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='rcbScroll rcbWidth']/ul[@class='rcbList']//li[last()]")))
    
  • Using XPATH and innerText:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//li[starts-with(., 'Uri Aran')]")))
    
  • 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
    
  • Related