使用Selenium with Python自动化测试工具
标签(空格分隔): python
Selenium: 自动化测试工具
Selenium with Python文档: http://selenium-python.readthedocs.io/
参考文档:Python爬虫利器五之Selenium的用法
PhantomJS:无界面的,可脚本编程的WebKit浏览器引擎 参考:http://cuiqingcai.com/2577.html
使用Selenium自动登录支付宝交电费网站:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
# 先访问首页,否则会跳转登录页,域名不同,cookie导入不进去
driver.get("https://jiaofei.alipay.com")
# 添加cookie
cc = [{'secure': False, 'name': 'zone', 'httpOnly': False, 'domain': '.alipay.com', 'path': '/', 'value': 'RZ11A'},
{}
]
for x in cc:
driver.add_cookie(x)
# 再访问交电费页面
driver.get("https://jiaofei.alipay.com/fare/ebppChargeEntering.htm?chargeType=electric&province=%25C9%25C2%25CE%25F7&city=%25CE%25F7%25B0%25B2")
try:
# 显示等待出现需要的id元素才开始继续执行
element = WebDriverWait(driver, 100).until(
EC.presence_of_element_located((By.ID, "billKey"))
)
# 打印cookie
c = driver.get_cookies()
print(c)
# 隐式等待3秒
driver.implicitly_wait(3)
# 填写表单
element = driver.find_element_by_xpath("//select[@name='chargeInst']")
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
print("Value is: %s" % option.get_attribute("value"))
if option.get_attribute("value")=='XAGDGS1401':
option.click()
# 简易用法
# select = Select(driver.find_element_by_id('chargeCompany'))
# select.select_by_index(1)
# select.select_by_visible_text("西安供电公司")
# select.select_by_value('XAGDGS1401')
driver.implicitly_wait(3)
# 填写表单
elem = driver.find_element_by_id("billKey")
elem.send_keys("1234567890")
finally:
pass
# driver.quit()
# 输入回车
# elem.send_keys(Keys.RETURN)
# print(driver.page_source)
# driver.close()