Python-Selenium2做Web自动化测试(11)-下拉框处理、分页处理

一、下拉框处理
下拉框也是 web 页面上非常常见的功能,要想定位下拉框中的内容,首先需要定位到下拉框;

引用网友的Html文件
drop_down.html



<select id="ShippingMethod" onchange="updateShipping(options[selectedIndex]);"
name="ShippingMethod">
<option value="12.51">UPS Next Day Air ==> $12.51option>
<option value="11.61">UPS Next Day Air Saver ==> $11.61option>
<option value="10.69">UPS 3 Day Select ==> $10.69option>
<option value="9.03">UPS 2nd Day Air ==> $9.03option>
<option value="8.34">UPS Ground ==> $8.34option>
<option value="9.25">USPS Priority Mail Insured ==> $9.25option>
<option value="7.45">USPS Priority Mail ==> $7.45option>
<option value="3.20" selected="">USPS First Class ==> $3.20option>
select>

保存并通过浏览器打开.
我们来通过脚本选择下拉列表里的$10.69:

#-*-coding=utf-8
from selenium import webdriver
import os,time
chromedriver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
driver=webdriver.Chrome(chromedriver)
file_path = 'file:///' + os.path.abspath('drop_down.html')
driver.get(file_path)
time.sleep(2)
#先定位到下拉框
m=driver.find_element_by_id("ShippingMethod")
#再点击下拉框下的选项
m.find_element_by_xpath("//option[@value='10.69']").click()
time.sleep(3)
driver.quit()

二、分页处理
对于 web 页面上的分页功能:获取总页数、翻页操作(上一页,下一页)

#coding=utf-8
from selenium import webdriver
from time import sleep
import os

chromedriver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
driver=webdriver.Chrome(chromedriver)
driver.get("https://passport.baidu.com/v2/?reg&tt=1439117223717&gid=4C7B13B-024E-43E5-BC98-9AEA8B98EE1E&tpl=mn&u=https%3A%2F%2Fwww.baidu.com%2F")
#登录系统
driver.find_element_by_id("user_name").clear()
driver.find_element_by_id("user_name").send_keys("username")
driver.find_element_by_id("user_pwd").clear()
driver.find_element_by_id("user_pwd").send_keys("password")
driver.find_element_by_id("dl_an_submit").click()
sleep(2)
#获取所有分页的数量,并打印
total_pages=len(driver.find_element_by_tag_name("select").find_elements_by_t
ag_name("option"))
print "total page is %s" %(total_pages)
sleep(3)
#再次获取所分页,并执行循环翻页操作
pages=driver.find_element_by_tag_name("select").find_elements_by_tag_name("o
ption")
for page in pages:
page.click()
sleep(2)
sleep(3)

你可能感兴趣的:(Web自动化测试,软件测试)