目錄
一、查看被測應(yīng)用元素信息
二、Select的下拉框怎么定位
其思路也是獲取下拉的選項(xiàng)框,循環(huán)遍歷尋找匹配的index,找到便設(shè)置成選中屬性
三、非select的下拉框如何定位?
?在編寫webUI自動(dòng)化過程中,有些元素的定位,不能直接通過id、name等快速定位到。這些特殊的元素定位就需要我們了解和學(xué)習(xí)解決方案,例如下拉框、radio/checkbox等。本文一起來了解一下,下拉列表框該定位。
一、查看被測應(yīng)用元素信息
被測應(yīng)用如圖,禪道的添加用戶頁面,有一個(gè)部門的選項(xiàng),是下拉列表框,這種類型的如何定位呢?
二、Select的下拉框怎么定位
?F12打開控制,點(diǎn)擊具體的元素,看到它的屬性
select標(biāo)簽,name和id都是'dept'?,試試如下定位fang
s1= Select(driver.find_element(By.ID,'dept'))
s1.selec_by_index(1)
也可以封裝成一個(gè)方法
def select_by_index(self, By, by_value, index):
"""
根據(jù)index進(jìn)行選擇
by 定位方式
by_value 定位值
index 下標(biāo)
"""
select = self.driver.find_element(By, by_value)
depts = Select(select)
depts.select_by_index(index)
其中select_by_index是selenium自有方法源碼,可直接調(diào)用,如下是源碼信息
def select_by_index(self, index):
"""Select the option at the given index. This is done by examining the
"index" attribute of an element, and not merely by counting.
:Args:
- index - The option at this index will be selected
throws NoSuchElementException If there is no option with specified index in SELECT
"""
match = str(index)
for opt in self.options:
if opt.get_attribute("index") == match:
self._set_selected(opt)
return
raise NoSuchElementException(f"Could not locate element with index {index}")
其思路也是獲取下拉的選項(xiàng)框,循環(huán)遍歷尋找匹配的index,找到便設(shè)置成選中屬性
三、非select的下拉框如何定位?
實(shí)際情況,有用input標(biāo)簽的下拉框功能,怎么定位呢?如下圖
只能通過模擬人手動(dòng)點(diǎn)的方式觸發(fā)事件
非select的下拉框可以通過以下方式抓取元素:
- 使用click()方法模擬用戶點(diǎn)擊下拉框,展開下拉選項(xiàng)。
- 使用find_elements_by_xpath()方法定位所有下拉選項(xiàng)的元素并存儲(chǔ)到一個(gè)列表中。
- 遍歷下拉選項(xiàng)列表,找到目標(biāo)選項(xiàng),并使用click()方法點(diǎn)擊它。
- 如果需要輸入內(nèi)容,可以獲取下拉框的input元素進(jìn)行操作。
示例代碼:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
# 定位下拉框并點(diǎn)擊展開
dropdown = driver.find_element_by_xpath('//input[@name="wd"]')
dropdown.click()
# 定位下拉選項(xiàng)并點(diǎn)擊目標(biāo)選項(xiàng)
options = driver.find_elements_by_xpath('//ul[@class="sug"]/li')
for option in options:
if option.text == "Selenium":
option.click()
break
# 獲取下拉框的input元素并輸入內(nèi)容(可選)
input_box = driver.find_element_by_xpath('//input[@name="wd"]')
input_box.send_keys("使用Selenium進(jìn)行自動(dòng)化測試")
其實(shí)也是仿寫了上面selenium的select_by_index 思路循環(huán)遍歷,只是先要通過click方法觸發(fā)一下options的展示。文章來源:http://www.zghlxwxcb.cn/news/detail-666750.html
四、思考
我們在學(xué)習(xí)selenium UI自動(dòng)化過程中,可以多去看源碼,看看官方的解決思路是怎么樣的,多看多實(shí)踐,有些也可以為我所用。文章來源地址http://www.zghlxwxcb.cn/news/detail-666750.html
到了這里,關(guān)于selenium自動(dòng)化元素定位之下拉列表框的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!