使用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("http://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()