使用 selenium python 从下拉框中选择每个选项

问题描述 投票:0回答:2

我正在尝试从网站中提取一些数据。然而,该网站具有层次结构。它的顶部有一个下拉菜单,其选项值为 URL。因此,我的方法是:

  1. 找到下拉框,
  2. 选择一个选项,
  3. 提取一些数据,并且
  4. 对所有可用选项重复步骤 2 至 4。

下面是我的代码,我能够在默认选择的选项(第一个)下提取数据。但我得到了错误

Message: Element not found in the cache - perhaps the page has changed since it was looked up
。我的浏览器似乎没有切换到新页面。我尝试过
time.sleep()
driver.refresh()
,但失败了...任何建议表示赞赏!

<select class="form-control"> 
    <option value="/en/url1">001 Key</option>
    <option value="/en/url2">002 Key</option>
</select>
# select the dropdown menu
select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
# get all options
options = select_box.options

for ele_index, element in enumerate(options):
    # select a url
    select_box.select_by_index(ele_index)
    time.sleep(5)
    print element.text

    # extract page data
    id_comp_html = driver.find_elements_by_class_name('HorDL')
    for q in id_comp_html:
        print q.get_attribute("innerHTML")
        print "============="

更新1(基于alecxe的解决方案)

# dropdown menu
select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
options = select_box.options

for ele_index in range(len(options)):
    # select a url
    select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
    print select_box.options[ele_index].text
    select_box.select_by_index(ele_index)
    # print element.text
    # print "======"
    driver.implicitly_wait(5)
    id_comp_html = driver.find_elements_by_class_name('HorDL')
    for q in id_comp_html:
        print q.get_attribute("innerHTML")
        print "============="
python html selenium
2个回答
1
投票

您的

select_box
element
引用已过时,您必须在循环内操作选项索引时“重新查找”选择元素:

# select the dropdown menu
select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
# get all options
options = select_box.options

for ele_index in range(len(options)):
    # select a url
    select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
    select_box.select_by_index(ele_index)

    # ...
    element = select_box.options[ele_index]

选择选项并提取所需数据后,您可能还需要导航回来。这可以通过

driver.back()
来完成。


1
投票

从您对网站和代码的描述来看,似乎从下拉列表中选择一个选项会将您带到另一个页面;因此,在 for 循环中第一次迭代后,您已移至不同的页面,而您的

options
变量指向前一页中的元素。

针对您的情况(在这种情况下可能是最好的解决方案)的一种解决方案是存储选项值(即网址),并通过

.get()
方法直接导航到这些网址。

否则,您需要保留一个计数器并在每次迭代时获取下拉列表的内容,在每次迭代后向后导航,在这种情况下这两种选择都是不必要的。

© www.soinside.com 2019 - 2024. All rights reserved.