簡體   English   中英

Python Selenium選擇Bootstrap下拉菜單

[英]Python Selenium select Bootstrap drop down menu

如何使用Python Selenium從Bootstrap下拉菜單中選擇元素? 我的下拉HTML看起來像:

  <select type="select" class="selectpicker form-control" id="selFoo" >
        <option data-hidden="true">Make a selection</option>

        <option>Foo</option>
        <option>Bar</option>
        <option>Baz</option>

  </select>

我已經嘗試過使用硒選擇模塊,但收到如下錯誤:

selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted 

如果要從示例下拉列表中選擇“欄”,請執行以下操作:

browser = webdriver.Firefox(profile)
browser.get(hostname)
sleep(1) # wait for page to render    

dropdown = browser.find_element_by_css_selector("button[data-id=selFoo]")
dropdown.click()
sleep(1) # probably not necessary
option   = browser.find_element_by_css_selector("ul[role=menu] a[data-normalized-text='<span class=\"text\">Bar</span>']")
option.click()

僅在Firefox中測試過。

您可以使用SeleniumSelect模塊。 試試下面的代碼:

from selenium import webdriver
from selenium import selenium.webdriver.support.select

dropdown = Select(driver.find_element_by_css_selector(#selFoo))
dropdown.select_by_value('Foo')   # will select Foo option

有關更多詳細信息,請參閱選擇

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select

dropdown = Select(WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id("selFoo")))
dropdown.select_by_visible_text("Baz")

這應該工作。 如果沒有,您可以嘗試在這兩行之前添加它。

WebDriverWait(driver, 10).until(lambda driver: driver.execute_script("return jQuery.active === 0"))

這樣可以確保在完成jQuery前沒有任何事情發生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM