【问题标题】:How to select a drop-down menu value with Selenium using Python?如何使用 Python 使用 Selenium 选择下拉菜单值?
【发布时间】:2011-12-13 15:07:27
【问题描述】:

我需要从下拉菜单中选择一个元素。

例如:

<select id="fruits01" class="select" name="fruits">
  <option value="0">Choose your fruits:</option>
  <option value="1">Banana</option>
  <option value="2">Mango</option>
</select>

1) 首先我必须点击它。我这样做:

inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()

2) 之后我必须选择好的元素,比如说Mango

我尝试使用inputElementFruits.send_keys(...) 进行操作,但没有成功。

【问题讨论】:

    标签: python selenium selenium-webdriver webdriver html-select


    【解决方案1】:

    Selenium 提供了一个方便的 Select class 来使用 select -&gt; option 构造:

    from selenium import webdriver
    from selenium.webdriver.support.ui import Select
    
    driver = webdriver.Firefox()
    driver.get('url')
    
    select = Select(driver.find_element_by_id('fruits01'))
    
    # select by visible text
    select.select_by_visible_text('Banana')
    
    # select by value 
    select.select_by_value('1')
    

    另见:

    【讨论】:

    • 这是一个很好的方法,应该是事实上的方法。但是,我会注意到,如果表单的作者没有正确设置选择 HTML 元素,您可能必须使用更钝的“xpath”版本。如果只是使用输入字段,xpath 应该可以工作。
    • 我们可以通过 xpath 而不是 by_id 找到元素吗?在选择函数中?
    • 这不会为我触发输入事件:(我必须自己做,如此处所述:stackoverflow.com/questions/2856513/…
    • 非常好。这清理了我正在使用的一些可怕的黑客攻击。
    【解决方案2】:

    除非您的点击触发了某种 ajax 调用来填充您的列表,否则您实际上不需要执行点击。

    只需找到元素,然后枚举选项,选择您想要的选项。

    这是一个例子:

    from selenium import webdriver
    b = webdriver.Firefox()
    b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
    

    您可以阅读更多内容:
    https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver

    【讨论】:

    • 仅供参考,使用Select 类使问题更容易解决,请参阅我发布的答案。
    • 如果我使用find_by_id,我该怎么办?那我该如何提供价值呢?另外,如何找到元素的xpath
    • @PrakharMohanSrivastava(和其他人)来查找 XPath,如果您在 Chrome 开发工具中突出显示了源,您可以右键单击源,然后选择 Copy --> XPath 以获取完整的 XPath那个元素。
    • 如果我没有文本的名称怎么办?我只想要菜单中的第一个元素。
    • @alecxe 的答案中链接的 Select 类提供了一个 select_by_index 函数,看起来就是您想要的。
    【解决方案3】:

    希望这段代码对你有所帮助。

    from selenium.webdriver.support.ui import Select
    

    带有 id 的下拉元素

    ddelement= Select(driver.find_element_by_id('id_of_element'))
    

    带有 xpath 的下拉元素

    ddelement= Select(driver.find_element_by_xpath('xpath_of_element'))
    

    带有 CSS 选择器的下拉元素

    ddelement= Select(driver.find_element_by_css_selector('css_selector_of_element'))
    

    从下拉列表中选择“香蕉”

    1. 使用下拉索引

    ddelement.select_by_index(1)

    1. 使用下拉菜单的值

    ddelement.select_by_value('1')

    1. 您可以使用匹配下拉菜单中显示的文本。

    ddelement.select_by_visible_text('Banana')

    【讨论】:

    • 有没有办法把它变成一个代码行?而不是制作一个变量然后应用 Select?谢谢
    • 你可以像这样写一行代码。 Select(driver.find_element_by_id('id_of_element')).select_by_index(1)
    • 最佳答案!谢谢!
    【解决方案4】:

    首先你需要导入 Select 类,然后你需要创建 Select 类的实例。 创建 Select 类的实例后,您可以对该实例执行选择方法以从下拉列表中选择选项。 这是代码

    from selenium.webdriver.support.select import Select
    
    select_fr = Select(driver.find_element_by_id("fruits01"))
    select_fr.select_by_index(0)
    

    【讨论】:

      【解决方案5】:

      根据提供的 HTML:

      <select id="fruits01" class="select" name="fruits">
        <option value="0">Choose your fruits:</option>
        <option value="1">Banana</option>
        <option value="2">Mango</option>
      </select>
      

      要从 菜单中选择&lt;option&gt; 元素,您必须使用Select 。此外,由于您必须与 交互,因此您必须为element_to_be_clickable() 诱导WebDriverWait

      要从 中选择带有Mango 文本的&lt;option&gt;,您可以使用以下Locator Strategies 之一:

      • 使用ID属性和select_by_visible_text()方法:

        from selenium import webdriver
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.webdriver.support.ui import Select
        
        select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01"))))
        select.select_by_visible_text("Mango")
        
      • 使用 CSS-SELECTORselect_by_value() 方法:

        select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.select[name='fruits']"))))
        select.select_by_value("2")
        
      • 使用 XPATHselect_by_index() 方法:

        select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//select[@class='select' and @name='fruits']"))))
        select.select_by_index(2)
        

      【讨论】:

        【解决方案6】:

        我尝试了很多东西,但我的下拉菜单在表格内,我无法执行简单的选择操作。只有以下解决方案有效。在这里,我突出显示下拉元素并按下向下箭头,直到获得所需的值 -

                #identify the drop down element
                elem = browser.find_element_by_name(objectVal)
                for option in elem.find_elements_by_tag_name('option'):
                    if option.text == value:
                        break
        
                    else:
                        ARROW_DOWN = u'\ue015'
                        elem.send_keys(ARROW_DOWN)
        

        【讨论】:

          【解决方案7】:

          您不必单击任何内容。 通过 xpath 或任何您选择的方式使用查找,然后使用发送密钥

          对于您的示例: HTML:

          <select id="fruits01" class="select" name="fruits">
              <option value="0">Choose your fruits:</option>
              <option value="1">Banana</option>
              <option value="2">Mango</option>
          </select>
          

          Python:

          fruit_field = browser.find_element_by_xpath("//input[@name='fruits']")
          fruit_field.send_keys("Mango")
          

          就是这样。

          【讨论】:

            【解决方案8】:

            你可以很好地使用css选择器组合

            driver.find_element_by_css_selector("#fruits01 [value='1']").click()
            

            将attribute = value css选择器中的1改为想要的水果对应的值。

            【讨论】:

              【解决方案9】:

              通过这种方式,您可以选择任何下拉菜单中的所有选项。

              driver.get("https://www.spectrapremium.com/en/aftermarket/north-america")
              
              print( "The title is  : " + driver.title)
              
              inputs = Select(driver.find_element_by_css_selector('#year'))
              
              input1 = len(inputs.options)
              
              for items in range(input1):
              
                  inputs.select_by_index(items)
                  time.sleep(1)
              

              【讨论】:

              • 我正在尝试使用 for items in range(1,input1): inputs.select_by_index(items) 逐一选择,但它从第二个索引开始。我怎样才能得到第一个值?
              • 我认为你应该从 0 开始你的循环。希望它不会逃脱第一个选项。
              【解决方案10】:

              它适用于选项值:

              from selenium import webdriver
              b = webdriver.Firefox()
              b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()
              

              【讨论】:

                【解决方案11】:
                from selenium.webdriver.support.ui import Select
                driver = webdriver.Ie(".\\IEDriverServer.exe")
                driver.get("https://test.com")
                select = Select(driver.find_element_by_xpath("""//input[@name='n_name']"""))
                select.select_by_index(2)
                

                它会正常工作

                【讨论】:

                • 不会在之前的答案中添加任何内容。
                【解决方案12】:

                没有&lt;select&gt;的下拉菜单

                每当我遇到没有&lt;select&gt; 标签的下拉菜单时,这对我有用

                # Finds the dropdown option by its text
                driver.find_element_by_xpath("//*[text()='text of the option']")
                

                导入ActionChains模块

                from selenium.webdriver.common.action_chains import ActionChains
                

                使用ActionChains点击元素

                drp_element = driver.find_element_by_xpath("//*[text()='text of the option']")
                action = ActionChains(driver)
                action.click(on_element=drp_element).perform()
                

                【讨论】:

                  【解决方案13】:

                  在浏览了很多这样的帖子后,我设法找到了一个解决方案,让我可以在下拉列表中选择一个项目。我以各种方式尝试了 .send_keys、click() 和 Select,但均未成功。在单击下拉列表中的项目之前,最终将 click() 命令发送到下拉列表 3 次。

                  dropMenu = browser.find_element_by_id('cmbDeviceType')
                  dropMenu.click()
                  dropMenu.click()
                  dropMenu.click()
                  
                  deviceType = browser.find_element_by_id('cmbDeviceType_DDD_L_LBI16T0')
                  deviceType.click()
                  

                  绝对不是超级漂亮,但它确实有效。

                  希望这对某人有所帮助。这是在 Firefox 88.0.1 上使用 Python3.7.7 完成的。

                  【讨论】:

                    【解决方案14】:

                    使用selenium.webdriver.support.ui.Select 类处理下拉选择的最佳方式,但由于设计问题或 HTML 的其他问题,有时它无法按预期工作。

                    在这种情况下,您也可以使用execute_script() 作为替代解决方案,如下所示:-

                    option_visible_text = "Banana"
                    select = driver.find_element_by_id("fruits01")
                    
                    #now use this to select option from dropdown by visible text 
                    driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, option_visible_text);
                    

                    【讨论】:

                      【解决方案15】:
                      dropdown1 = Select(driver.find_element_by_name("fruits"))
                      dropdown1.select_by_visible_text('banana')
                      

                      【讨论】:

                      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
                      【解决方案16】:
                      1. 列表项

                      公共类 ListBoxMultiple {

                      public static void main(String[] args) throws InterruptedException {
                          // TODO Auto-generated method stub
                          System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
                          WebDriver driver=new ChromeDriver();
                          driver.get("file:///C:/Users/Amitabh/Desktop/hotel2.html");//open the website
                          driver.manage().window().maximize();
                      
                      
                          WebElement hotel = driver.findElement(By.id("maarya"));//get the element
                      
                          Select sel=new Select(hotel);//for handling list box
                          //isMultiple
                          if(sel.isMultiple()){
                              System.out.println("it is multi select list");
                          }
                          else{
                              System.out.println("it is single select list");
                          }
                          //select option
                          sel.selectByIndex(1);// you can select by index values
                          sel.selectByValue("p");//you can select by value
                          sel.selectByVisibleText("Fish");// you can also select by visible text of the options
                          //deselect option but this is possible only in case of multiple lists
                          Thread.sleep(1000);
                          sel.deselectByIndex(1);
                          sel.deselectAll();
                      
                          //getOptions
                          List<WebElement> options = sel.getOptions();
                      
                          int count=options.size();
                          System.out.println("Total options: "+count);
                      
                          for(WebElement opt:options){ // getting text of every elements
                              String text=opt.getText();
                              System.out.println(text);
                              }
                      
                          //select all options
                          for(int i=0;i<count;i++){
                              sel.selectByIndex(i);
                              Thread.sleep(1000);
                          }
                      
                          driver.quit();
                      
                      }
                      

                      }

                      【讨论】:

                      • 该问题明确要求提供 Python 解决方案,非常感谢您的回答,但在此上下文中不需要,因为它是用 Java 编写的。
                      • 抱歉,这不是问题和标签中提到的 Python
                      猜你喜欢
                      • 2016-07-28
                      • 2022-07-08
                      • 1970-01-01
                      • 2020-11-22
                      • 1970-01-01
                      • 1970-01-01
                      • 2020-05-09
                      • 2023-04-01
                      相关资源
                      最近更新 更多