如何在Python Selenium的下拉列表中选择href这个选项?

时间:2018-07-13 07:56:35

标签: python selenium web-scraping

我正在尝试构建一个简单的刮板,以加载​​位于三个不同区域(在下拉值内)的位置地址,然后将所有这些地址复制为文本。我设法使用python Selenium在Chrome中加载了网站,然后单击链接(该网站每次加载都会更改一个动态数字。现在显示为2801157,但是每次都会更改)。但是,单击下拉列表后,我不知道为什么不能单击这些选项值(即一次在“ li”内的香港岛,九龙,新界)。隐藏的html部分在许多div下;相关部分如下:

<div class="hkoutlettop_select">
  <select name="" class="hkoutlet_select selDistrict" tabindex="1" sb="28011577" style="display: none;">
    <option value="Hong Kong Island">Hong Kong Island</option>
    <option value="Kowloon">Kowloon</option>
    <option value="New Territories">New Territories</option>
  </select>
  <div id="sbHolder_28011577" class="sbHolder" tabindex="1">
    <a id="sbToggle_28011577" href="#" class="sbToggle sbToggleOpen"></a><a id="sbSelector_28011577" href="#" class="sbSelector">Hong Kong Island</a>
    <ul id="sbOptions_28011577" class="sbOptions" style="top: 22px; max-height: 715px;">
      <li><a href="#Hong Kong Island" rel="Hong Kong Island" class="">Hong Kong Island</a></li>
      <li><a href="#Kowloon" rel="Kowloon" class="">Kowloon</a></li>
      <li><a href="#New Territories" rel="New Territories" class="">New Territories</a></li>
    </ul>
  </div>
</div>

这是我的代码

# loading Chrome browswer, add useragent options
driver = webdriver.Chrome(chrome_options=options)

# wait a random amount of seconds. random_time is a list of integers
driver.implicitly_wait(random_time)

# the restaurant's website
driver.get(url)

# This gets the dynamic id
WebElement_Dynamic_ID_selector = driver.find_element_by_class_name("sbSelector").get_attribute("id")

# This gets the dynamic id, not sure if I need to do this though
WebElement_Dynamic_ID_options = driver.find_element_by_class_name("sbOptions").get_attribute("id")

# select dropdown once it is available
district_dropdown = WebDriverWait(driver, 100).until(EC.presence_of_element_located((By.ID, WebElement_Dynamic_ID_selector)))

# click dropdown
district_dropdown.click()

# wait for areas to show up
area_list_dropdown = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.ID,WebElement_Dynamic_ID_options)))

# I'm stuck

2 个答案:

答案 0 :(得分:1)

尝试使用以下解决方案:

driver.get(url)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "sbSelector"))).click()
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Kowloon"))).click()

答案 1 :(得分:0)

尝试更改WebElement_Dynamic_ID_options的定位符:

WebElement_Dynamic_ID_options = driver.find_elements_by_xpath("//ul[@class='sbOptions']/li/a")
for values in WebElement_Dynamic_ID_options:
    values.click() //or any action you need