selenium處理頁面常見問題(三):select下拉選項菜單

1. select標籤也很常見,通常有單選和多選兩種,單選標籤格式常見如下:

<select name="NR" id="nr">
    <option value="10" selected="">每頁顯示10條</option>
    <option value="20">每頁顯示20條</option>
    <option value="50">每頁顯示50條</option>
</select>

對於多選select,則多了一個multiple屬性,指定爲多選菜單

<select multiple="multiple" size="2">
  <option value ="volvo">Volvo</option>
  <option value ="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

2. selenium處理select也很簡單,一種方法是找到select元素,直接點擊其下的選項

select = driver.find_element_by_id("nr")
driver.find_element_by_xpath('//select[@id="nr"]/option[2]').click()

第二種方法是使用Select模塊,使用前先引入,注意引入路徑應爲:

from selenium.webdriver.support.select import Select

找到select元素,封裝到Select模塊中,然後就可以調用Select自帶的多種方法,使用起來比較方便簡單

select = driver.find_element_by_id("nr")
Select(select).select_by_index(0)

Select模塊提供的方法有以下幾種,其中取消對應...選項的都是多選菜單纔有的方法,用到單選菜單上會報錯:

select_by_index() :通過索引定位
select_by_value() :通過value值定位
select_by_visible_text() :通過文本值定位
deselect_all() :取消所有選項
deselect_by_index() :取消對應index選項
deselect_by_value() :取消對應value選項
deselect_by_visible_text() :取消對應文本選項
first_selected_option() :返回第一個選項
all_selected_options() :返回所有的選項

最後是一個完整的例子,以百度首頁設置菜單中搜索設置中每次顯示條數爲例:

from selenium import webdriver
from time import sleep

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select

class Test_Select:
    def setup(self):
        self.driver = webdriver.Chrome(r"D:\Program Files\chromedriver.exe")
        self.driver.get(r"https://www.baidu.com")
        self.driver.implicitly_wait(10)
        self.driver.maximize_window()
    def test_select(self):
        driver = self.driver
        menu = driver.find_element_by_link_text("設置")
        ActionChains(driver).move_to_element(menu).perform()
        driver.find_element_by_xpath('//div[@id="wrapper"]/div[6]/a[1]').click()
        # driver.find_element_by_link_text("搜索設置").click()
        sleep(3)
        # 1. 找到select標籤和其下的option,點擊即可
        select = driver.find_element_by_id("nr")
        driver.find_element_by_xpath('//select[@id="nr"]/option[2]').click()
        sleep(3)
        # 2. 使用Select模塊封裝的方法,先找到select元素,再封裝爲Select,再執行方法
        Select(select).select_by_index(0)
        sleep(3)
        # select_by_value()
        Select(select).select_by_value("50")
        sleep(4)
        # select_by_visible_text()
        Select(select).select_by_visible_text("每頁顯示10條")
        sleep(3)

    def teardown(self):
        self.driver.quit()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章