1. 程式人生 > >Selenium系列(十) - 針對Select下拉框的操作和原始碼解讀

Selenium系列(十) - 針對Select下拉框的操作和原始碼解讀

如果你還想從頭學起Selenium,可以看看這個系列的文章哦!

https://www.cnblogs.com/poloyy/category/1680176.html

 

其次,如果你不懂前端基礎知識,需要自己去補充哦,博主暫時沒有總結(雖然我也會,所以我學selenium就不用複習前端了哈哈哈...)

 

首先,將下面html程式碼儲存到一個檔案中

後續的程式碼小案例都是訪問此html的<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>下拉框</title>
</head>
<body>

<select id="pro"> <option value="gd">廣東</option> <option value="hb">湖北</option> <option value="gj">北京</option> </select>

<select id="city" multiple> <option value="gz">廣州</option> <option value="wh">武漢</option> <option value="gj">北京</option> </select> </body> </html>

注意

若select下拉框有 multiple 屬性,則可以多選option,但這種情況不常見

 

關於下拉框的操作

  • 返回所有選項
  • 返回所有被選中的選項
  • 通過value屬性選中or取消選中選項
  • 通過index索引選中or取消選中選項
  • 通過標籤間文字選中or取消選中選項
  • 取消選中所有選項

 

返回選項&選中操作

# !/usr/bin/env python
# -*- coding: utf-8 -*-

"""
__title__  =
__Time__   = 2020/3/25 17:52
__Author__ = 小菠蘿測試筆記
__Blog__   = https://www.cnblogs.com/poloyy/
"""
from time import sleep

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

driver = webdriver.Chrome("../resources/chromedriver.exe")

# 將html檔案更改為自己的路徑
driver.get("file:///C:/下拉框.html")
driver.maximize_window()

# 找到select標籤元素
pro = Select(driver.find_element_by_id("pro"))

# 返回所有選項
for option in pro.options:
    print(option.text)

# 返回所有被選中的選項
for option in pro.all_selected_options:
    print(option.text)

# 通過value選中
pro.select_by_value("bj")
sleep(1)

# 通過index選中
pro.select_by_index(1)
sleep(1)

# 通過標籤文字選中
pro.select_by_visible_text("廣東")

 

取消選中操作

# 找到id=city的下拉框
city = Select(driver.find_element_by_id("city"))

# 全選
for option in city.options:
    if not option.is_selected():
        city.select_by_visible_text(option.text)
sleep(1)

# 根據value取消選中
city.deselect_by_value("bj")
sleep(1)

# 根據index取消選中
city.deselect_by_index(0)
sleep(1)

# 根據標籤文字選中
city.deselect_by_visible_text("武漢")
sleep(1)

# 全選
for option in city.options:
    if not option.is_selected():
        city.select_by_visible_text(option.text)
sleep(1)

# 取消選中所有選項
city.deselect_all()

知識點

取消操作只適用於添加了multiple的下拉框,否則會報錯

    raise NotImplementedError("You may only deselect options of a multi-select")
NotImplementedError: You may only deselect options of a multi-select

 

Select原始碼解讀

class Select(object):

    def __init__(self, webelement):
        """
        Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
        then an UnexpectedTagNameException is thrown.

        :Args:
         - webelement - element SELECT element to wrap

        Example:
            from selenium.webdriver.support.ui import Select \n
            Select(driver.find_element_by_tag_name("select")).select_by_index(2)
        """

知識點

  • 例項化 Select 需要傳入 select 下拉框的 webelement 
  • 若傳入 webelement 的 tag_name 不是 <select>..</select> 標籤,則會丟擲異常 UnexpectedTagNameException 

&n