1. 程式人生 > 實用技巧 >python+selenium2自動化---使用Select類實現下拉列表的定位

python+selenium2自動化---使用Select類實現下拉列表的定位

用法:

1、先匯入Select類

from selenium.webdriver.support.select import Select

2、例項化,通過原始碼可知初始化物件的時候需要傳入下拉框元素物件:

3、示例程式碼

#form2.html
<!
DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="javascript:alert('test')"
> 省份: <select id="province" > <option value="bj">北京市</option> <option value="tj">天津市</option> <option value="sc">四川省</option> <option value="sd">山東省</option> <option value="hn">河南省</option>
</select> </form> </body> </html>

測試程式碼

from selenium import webdriver
import os
from time import sleep

from selenium.webdriver.support.select import Select


class TestCase():
    def __init__(self):
        self.driver = webdriver.Chrome()
        html_path = os.path.dirname(os.path.abspath(__file__
)) # 本地的html檔案地址拼接 file_path = "file:///" + html_path + '/form2.html' self.driver.get(file_path) self.driver.maximize_window() se = self.driver.find_element_by_id('province') self.select = Select(se) def test_single_select(self): """單選下拉框的測試""" # 根據值選擇 self.select.select_by_value('tj') sleep(2) # 根據索引選擇 self.select.select_by_index(0) sleep(2) # 根據文字選擇 self.select.select_by_visible_text('四川省') sleep(2) self.driver.quit() def test_multiple_slect(self): """多選下拉框的測試,需要在表單元素中新增multiple引數""" # 獲取所有選項標籤 options = self.select.options # 遍歷選中所有標籤 for option in options: option.click() sleep(2) selected_options = self.select.all_selected_options print('所有選中的選項:', selected_options) first_selected_option = self.select.first_selected_option print('第一個選中的選項值:', first_selected_option.get_attribute('value')) # 根據值反選 self.select.deselect_by_value('bj') sleep(2) # 根據索引反選 self.select.deselect_by_index(3) sleep(2) # 根據文字反選 self.select.deselect_by_visible_text('河南省') sleep(2) # 反選所有 self.select.deselect_all() sleep(2) self.driver.quit() if __name__ == '__main__': case = TestCase() # case.test_single_select() case.test_multiple_slect()