【问题标题】:selenium iterate through options in dropdown selectselenium 遍历下拉选择中的选项
【发布时间】:2016-02-22 17:05:26
【问题描述】:

我在 python 中使用 selenium,我有一个下拉列表,我正在尝试从中进行选择。本质上,我只想遍历所有选项,如下所示:

select first option 
  submit page 
  \\ do stuff
select second option 
  submit page 
  \\ do stuff
select third option 
  submit page 
  \\ do stuff
etc...

我知道如果您知道每个选项值是什么(您只需创建这些值的列表),就可以做到这一点,但是当您不知道是什么时,有没有一种方法可以遍历所有选项选项值是?

谢谢!

【问题讨论】:

  • Python 有类似 select_by_id 的东西吗?哪个是数字?

标签: python selenium selenium-webdriver


【解决方案1】:

您可以使用select.options 获取所有选项的列表。比你可以使用索引选择选项。

select = Select(driver.find_element_by_id("dropDown"))
options = select.options
for index in range(0, len(options) - 1):
    select.select_by_index(index)
    # do stuff

【讨论】:

    【解决方案2】:

    谢谢你的回答,问题,不应该是这样

    select = Select(driver.find_element_by_id("dropDown"))
    options = select.options
    for index in range(0, len(options)):
        select.select_by_index(index)
        # do stuff   
    

    【讨论】:

    • 这个答案和其他答案的唯一区别是第 3 行的 ` - 1`。请解释区别以及为什么它很重要。
    【解决方案3】:

    您可以简单地遍历所有选项:

    select = Select(driver.find_element_by_id("someId"))
    
    for opt in select.options:
        # for example
        print(opt.text)
        opt.click()
    

    【讨论】:

      猜你喜欢
      • 2019-11-11
      • 2019-05-28
      • 1970-01-01
      • 2021-05-24
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多