【Python教程】selenium操作点击显示下拉列表
所需工具:
Python
聪明的大脑
勤劳的双手
注意:本站只提供教程,不提供任何成品+工具+软件链接,仅限用于学习和研究。
处理下拉列表需要使用selenium中的工具类Select,常用方法如下:
示例脚本:
from selenium import webdriver from time import sleep from selenium.webdriver.support.select import Select class TestSelected(object): def setup(self): self.driver = webdriver.Chrome() self.driver.get("https://sahitest.com/demo/") def test_selected(self): #点“Select Test”链接 self.driver.find_element_by_xpath("/html/body/table/tbody/tr/td[1]/a[4]").click() #点第一个下拉框 se=self.driver.find_element_by_id("s1Id") #选中下拉框选项 select=Select(se) #循环打印下拉框选项 for options in select.options: print(options.text)
运行结果:
(2)操作多选列表
示例脚本:
from selenium import webdriver from time import sleep from selenium.webdriver.support.select import Select class TestSelected(object): def setup(self): self.driver = webdriver.Chrome() self.driver.get("https://sahitest.com/demo/") def test_multiselected(self): #点“Select Test”链接 self.driver.find_element_by_xpath("/html/body/table/tbody/tr/td[1]/a[4]").click() #列表多选框 mulsel = self.driver.find_element_by_id("s4Id") select2 = Select(mulsel) #选择列表中所有选项 for i in range(6): select2.select_by_index(i) #根据索引值反选 # select2.deselect_by_index(i) sleep(1) sleep(2) #反选所有 select2.deselect_all() self.driver.quit()
发表评论