常用WebDriver API 的用法----5

1:判断单选列表内容是否与预期一致

  

from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
driver=webdriver.Chrome()
#访问自定义网址
driver.get("D://table.html")
#获取select元素对象
select_element=driver.find_element_by_xpath("//select[@name='fruit']")
select=Select(select_element)
#获取所有下拉列表对象
all_option=select.options
#新建空列表用来存放option对象值
list_option_text=[]
exp_list=['桃子', '橘子', '西瓜']
for option in all_option:
    text=option.text
    list_option_text.append(text)
print(list_option_text==exp_list)

 result:

 True

2:操作多选列表

 html源码:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>操作单选下拉列表</title>
</head>
<body>
 <select name="fruit" size=3 multiple=true>
    <option id="peach" value="taozi">桃子</option>
    <option id="orange" value="juzi">橘子</option>
    <option id="watermelon" value="xigua">西瓜</option>
    
</body>
<html>

 操作源码:

from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
driver=webdriver.Chrome()
#访问自定义网址
driver.get("D://table.html")
#获取select元素对象
select_element=driver.find_element_by_xpath("//select[@name='fruit']")
select=Select(select_element)
#选中所有选项
select.select_by_index(0)
select.select_by_index(1)
select.select_by_index(2)
#打印所有选中的选项值
for option in select.all_selected_options:
    print(option.text)
#取消所有选中项
select.deselect_all()

 result:

  桃子
  橘子
  西瓜

3:操作可以输入的下拉列表

  html源码:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>操作单选下拉列表</title>
</head>
<body>
 <div style="position:relative;">
   <input list="pasta" id="select">
   <datalist id="pasta">
    <option>桃子1</option>
    <option>桃子2</option>
    <option>桃子3</option>
    <option>桃子4</option>
    <option>桃子5</option>
    <option>桃子6</option>
   </datalist>
 </div>
</body>
<html>

  操作代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver=webdriver.Chrome()
#访问自定义网址
driver.get("D://table.html")
#获取输入框元素
driver.find_element_by_id("select").send_keys("桃子1",Keys.ARROW_DOWN)
driver.find_element_by_id("select").send_keys(Keys.ARROW_DOWN)
# driver.find_element_by_id("select").send_keys(Keys.ENTER)

<!DOCTYPE html><html lang="en"><head>    <title>操作单选下拉列表</title></head><body> <div style="position:relative;">   <input list="pasta" id="select">   <datalist id="pasta">    <option>桃子1</option><option>桃子2</option><option>桃子3</option><option>桃子4</option><option>桃子5</option><option>桃子6</option>   </datalist> </div></body><html>

猜你喜欢

转载自www.cnblogs.com/Be-your-own-hero/p/11256291.html
今日推荐