【问题标题】:How to select dropdown on Selenium using Python如何使用 Python 在 Selenium 上选择下拉菜单
【发布时间】:2020-11-22 13:17:19
【问题描述】:

我正在尝试选择国家/地区,但不知何故它不起作用。下面的代码是我所做的。它不能正常工作。

<select name="state" class="form-control selectpicker">
                                        <option value=" ">Please select your state</option>
                                        <option>Alabama</option>
                                        <option>Alaska</option>
                                        <option>Arizona</option>
                                        <option>Arkansas</option>
                                        <option>California</option>
                                        <option>Colorado</option>
                                     </select>

我做了什么:browser.find_element_by_css_selector(".form-control.selectpicker [option='Alaska']").click()

【问题讨论】:

    标签: python-3.x selenium-webdriver drop-down-menu html-select webdriverwait


    【解决方案1】:

    要选择带有 Alaska 文本的&lt;option&gt;,您可以使用以下Locator Strategy

    • 使用xpath

      dropdown_menu = Select(browser.find_element_by_xpath("//select[@class='form-control selectpicker' and @name='state']"))
      dropdown_menu.select_by_visible_text('Alaska')
      

    理想情况下,您需要为element_to_be_clickable() 诱导WebDriverWait,您可以使用以下定位器策略

    • 在一行中使用CSS_SELECTOR

      Select(WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.form-control.selectpicker[name='state']")))).select_by_visible_text('Alaska')
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    参考

    您可以在以下位置找到一些相关讨论:

    【讨论】:

      猜你喜欢
      • 2022-07-08
      • 1970-01-01
      • 2023-03-25
      • 2022-11-11
      • 2023-01-19
      • 2016-07-28
      • 1970-01-01
      • 2011-12-13
      相关资源
      最近更新 更多