Selenium - 如何根据价值识别 li 项目

Selenium - How to identify li item based on value

我在要抓取的网页中有以下列表:

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

我想要 select 包含文本 Uri Aran 的项目。我怎样才能通过 Selenium 做到这一点?同一网站中还有其他 class 名称不同的列表。

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

你想要得到包含 Uri Aran 文字的那个。

要定位文本为 Uri Aran 的元素,您需要引入 WebDriverWait for the and you can use either of the following :

  • 使用CSS_SELECTORnth-child():

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.rcbScroll.rcbWidth > ul.rcbList li:nth-child(3)")))
    
  • 使用CSS_SELECTORnth-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)")))
    
  • 使用CSS_SELECTORlast-child:

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

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

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

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

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//li[starts-with(., 'Uri Aran')]")))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC