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

标签 python html selenium

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

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

下面是我的代码,我能够在默认选择的选项(第一个选项)下提取数据。但我收到错误消息:在缓存中找不到元素 - 也许页面自查找以来已更改。我的浏览器似乎没有切换到新页面。我尝试了 time.sleep()driver.refresh(),但失败了...任何建议表示赞赏!

###html
<select class="form-control"> 
    <option value="/en/url1">001 Key</option>
    <option value="/en/url2">002 Key</option>
</select>

### python code

# 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 "============="

最佳答案

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

# 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()来完成。

关于python - 使用 selenium python 从下拉框中选择每个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751916/

相关文章:

python - selenium.common.exceptions.NoSuchElementException : Message: Web element reference not seen before using GeckoDriver Firefox and Selenium with Python

selenium - 在 Selenium 自动化中,鼠标箭头移动是否可以用于测试用例

python - 你最喜欢的 Python 模拟库是什么?

html - 边框半径不适用于无序列表

javascript - 如何加密 HTML5 网络存储?

R Selenium右键单击下载文件

python - ajax 请求在 Django 中查看产生 404

python - 让 TensorFlow 做一些琐碎的事情时遇到困难

Python 正则表达式语句

javascript - 如何访问从 JSP 传递的参数作为 HTML 页面的隐藏输入?