【问题标题】:How to iterate through <li> that has <span> objects inside Selenium Python如何遍历在 Selenium Python 中具有 <span> 对象的 <li>
【发布时间】:2019-02-26 15:09:02
【问题描述】:

这是我要使用的页面的 HTML。在页面中,我想遍历一个下拉菜单,如下所示:

<ul class="col-24 position-absolute station-filter mobile-region s-padd-0-10">
      <li class=class="flex flex-wrap flex-display-block col-24 bg-white radius-5 overflow-scroll-y station-filter-inside">
          <span class="col-24 display-block padd-15-0 brd-bottom-1 station-select-region">Antofagasta</span>
          <span class="col-24 display-block padd-15-0 brd-bottom-1 station-select-region">Atacama</span>
          <span class="col-24 display-block padd-15-0 brd-bottom-1 station-select-region">Arica y parinacota</span>
          <span class="col-24 display-block padd-15-0 brd-bottom-1 station-select-region">Tarapaca</span> 
          <span class="col-24 display-block padd-15-0 brd-bottom-1 station-select-region">Biobio</span>

所以,我想做的是click() 每个跨度选项。

这就是我现在拥有的:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(r"C:\Users\juanc\OneDrive\Escritorio\chromedriver.exe")
driver.get("https://ww2.copec.cl/stations?check=punto")
driver.find_element_by_xpath("//*[@id='root']/div[1]/div/ul/li[1]/a").click()
result = driver.find_element_by_xpath('//*[@id="root"]/div[1]/div/ul/li[1]/ul/li')
options = result.find_element(By.CLASS_NAME("col-24 display-block padd-15-0 brd-bottom-1 station-select-region"))
for option in options:
    print(option.text)

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver web-scraping webdriver


    【解决方案1】:

    试试这个代码。希望对你有帮助。

    from selenium import webdriver
    
    driver = webdriver.Chrome(r"C:\Users\juanc\OneDrive\Escritorio\chromedriver.exe")
    
    driver.get("https://ww2.copec.cl/stations?check=punto")
    driver.find_element_by_xpath("//*[@id='root']/div[1]/div/ul/li[1]/a").click()
    results = driver.find_elements_by_css_selector('span.station-select-region')
    
    for rs in results:
        print(rs.text)
    

    输出:

    Antofagasta
    Atacama
    Arica y parinacota
    Tarapacá
    Biobio
    La araucanía
    Maule
    Los lagos
    Los rios
    Magallanes
    Aysén
    Valparaíso
    Metropolitana
    Coquimbo
    O higgins
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 2023-02-09
      • 2020-07-11
      • 2018-10-07
      • 1970-01-01
      • 2021-11-08
      • 2017-02-23
      • 2021-01-15
      相关资源
      最近更新 更多