【问题标题】:How to select a drop-down menu option value using Selenium - Python如何使用 Selenium - Python 选择下拉菜单选项值
【发布时间】:2016-07-28 01:58:38
【问题描述】:

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

<select class="chosen" id="fruitType" name="fruitType">
    <option value="">Select</option>
    <option value="1">jumbo fruit 1</option>
    <option value="2">jumbo fruit 2</option>
    <option value="3">jumbo fruit 3</option>
    <option value="4">jumbo fruit 4</option>
    <option value="5">jumbo fruit 5</option>
    <option value="8">jumbo fruit 6</option>
</select>

我已尝试使用此代码,

driver = webdriver.Firefox()
driver.find_element_by_xpath("//select[@name='fruitType']/option[text()='jumbo fruit 4']").click()

但它返回给我错误。 我怎样才能做到这一点。

【问题讨论】:

    标签: python selenium selenium-webdriver selenium-firefoxdriver


    【解决方案1】:

    来自official documentation

    from selenium.webdriver.support.ui import Select
    
    select = Select(driver.find_element_by_id('fruitType'))
    # Now we have many different alternatives to select an option.
    select.select_by_index(4)
    select.select_by_visible_text("jumbo fruit 4")
    select.select_by_value('4') #Pass value as string
    

    【讨论】:

      【解决方案2】:

      您可以像这样遍历所有选项:

      element = driver.find_element_by_xpath("//select[@name='fruitType']")
      all_options = element.find_elements_by_tag_name("option")
      for option in all_options:
          print("Value is: %s" % option.get_attribute("value"))
          option.click()
      

      【讨论】:

        【解决方案3】:

        您好,只需使用一行代码就可以了

        // please note the if in case you have to select a value form a drop down with tag 
        // name Select then use below code it will work like charm
        driver.find_element_by_id("fruitType").send_keys("jumbo fruit 4");
        

        希望对你有帮助

        【讨论】:

        • 对于这个答案,我收到以下错误 driver.find_element_by_id("fruitType").sendKeys("jumbo fruit 4"); AttributeError:“WebElement”对象没有属性“sendKeys”
        • 对不起,python 请使用 send_keys,我是 java 格式,所以这是一个拼写错误,我也更新了 python 的 sendkeys
        • 这样是不是像 select = Select(driver.find_element_by_xpath("//select[@id='fruitType' and @class='chosen']")) driver.find_element_by_id("fruitType") .send_keys("大果 4); ??
        • no no select statement not this line select = Select(driver.find_element_by_xpath("//select[@id='fruitType' and @class='chosen']")) .only this line driver .find_element_by_id("fruitType").send_keys("巨型水果 4);
        • 请使用通用等待驱动程序,因为错误显示 ElementNotVisibleException:消息:元素当前不可见,因此可能无法交互。在选择选项之前应用类似等待几秒钟的东西
        猜你喜欢
        • 2018-02-17
        • 1970-01-01
        • 2011-12-13
        • 2022-07-08
        • 2023-03-25
        • 2022-11-11
        • 2017-10-29
        • 1970-01-01
        相关资源
        最近更新 更多