1. 程式人生 > >Python+Selenium 簡單的例項

Python+Selenium 簡單的例項

1、Baidu_Serch.py

#coding=utf-8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException,TimeoutException
#from selenium.common.exceptions import   
from selenium.webdriver.support.ui import WebDriverWait # available since 
from selenium.webdriver.common.keys import Keys

from time import sleep

import os,time

driver = webdriver.Chrome()
print u"載入驅動完成.."
driver.get("https://ww.baidu.com")#載入頁面
print u"載入頁面完成.."

time.sleep(1)
 
# 方法一  
try:  
    assert u"百度一下" in driver.title  
    print ('Assertion baidu title pass.')  
except Exception as e:  
    print ('Assertion baidu title fail.', format(e)) 

driver.maximize_window() # 瀏覽器全屏顯示

print u"最大化頁面視窗完成.."

elem = driver.find_element_by_name("wd") # Find the query box
elem.send_keys(u"今日頭條" + Keys.RETURN)
#elem.submit()  提交表單方法

print u"輸入搜尋關鍵字..."

time.sleep(1) # Let the page load, will be added to the API

'''
#driver.find_element_by_id("kw").clear()
#driver.find_element_by_id("kw").send_keys(u"pyse自動化測試")
#driver.type("//*[@id='kw']",u"pyse自動化測試")
#driver.find_element_by_id("su").send_keys(Keys.ENTER)
#driver.click("//*[@id='su']")

#也可定位登陸按鈕,通過enter(回車)代替click()
driver.find_element_by_id("su").send_keys(Keys.ENTER)
'''
#方法一  採用包含判斷,建議第一種
try:
    driver.find_element_by_xpath("//*[@id='su']")
    print "校驗通過,百度一下按鈕存在"
except NoSuchElementException:
    assert 0, "校驗不通過"
#raw_input()#停止在當前游標處;
# 方法二
#time.sleep(1)
sleep(1)
#驗證 今日頭條_百度搜索 標題是否存在
if u"今日頭條_百度搜索" == driver.title :  
    print ('Assertion dayevenery title pass.')  
else:  
    print ('Assertion dayevenery title fail.')  
  
print driver.title
#raw_input()#停止在當前游標處;
#更多驗證方法
'''
try:  
            self.assertEqual(u"今日頭條_百度搜索", driver.title)
            
            print u"標題驗證 Pass"
except AssertionError as e:  
            print u"找不到這個標題"
            
try:  
            assert u"今日頭條_百度搜索" in driver.title
            self.assertFalse(driver.title)
            print u"標題驗證 True"
except AssertionError as e:  
            print u"找不到這個標題 Flase"
           
#判斷頁面上有無id為kw的元素
if is_element_exist("#kw") :
                driver.find_element_by_id("kw").send_keys("")
#判斷頁面有無標籤為input元素
if is_element_exist("input") :
                driver.find_element_by_tag_name("input").send_keys("eveneryday news!")
'''
#================================== 
try:  
    # we have to wait for the page to refresh, the last thing that seems to be updated is the title  
    WebDriverWait(driver, 10).until(lambda driver : driver.title.lower().startswith(""))  
  
    # You should see "cheese! - Google Search"  
    print u"等待時間,列印當前頁面的標題 :"+driver.title  
  
finally:
    print (u"-----> 請按Enter 鍵進行下一步操作...")    

    raw_input()#停止在當前游標處;

    #driver.close()
    print u"執行完成,即將關閉驅動..."

    driver.quit()#與close方法相同
    driver.quit()  
  
#==================================
2、ClikButton.py
#!C:/Python27
#coding=utf-8
from selenium import webdriver
#from selenium.webdriver.support.ui import WebDriverWait
#from selenium.webdriver.support.wait import WebDriverWait#WebDriverWait 匯入
from selenium.webdriver.common.keys import Keys
import os,time

driver = webdriver.Chrome()

driver.get("https://cas.sf-express.com/cas/login?service=http%3A%2F%2Fhos.sf-express.com%2Fframe.pvt&apptiket=dbe979f1b41f6ea23622b639ceb7acac18cf829000ed010c")

time.sleep(1)

driver.maximize_window() # 瀏覽器全屏顯示
print ('瀏覽器全屏顯示 ...')
#輸入使用者名稱和密碼
driver.find_element_by_id("username").send_keys("89003422")

driver.find_element_by_id("password").send_keys("518.com.12")
time.sleep(10)
#手動輸入驗證碼
#driver.find_element_by_id("verifyCode").send_keys("ABCD")
#點選登入
driver.find_element_by_xpath("//*[@id='loginForm']/div[5]/div/img").click()

time.sleep(8)

#開始執行點選事件 
#driver.find_element_by_id("outputButton").click()
print

print ('開始執行任務,執行間隔時間為10分鐘 ...')
print
for i in range(1,3):
    ISOTIMEFORMAT="%Y-%m-%d %X"
    strTime = time.strftime( ISOTIMEFORMAT, time.localtime())
    print u"正在執行第 ",i,"次...",strTime
    time.sleep(5)
    #執行點選事件
    driver.find_element_by_id("outputButton").click()
    time.sleep(60)
    #重新整理瀏覽器
    driver.refresh()
    time.sleep(535)
    print
    print u"已執行完第 ",i,u"次,","共延時",i*10,"分"
    print
print ('已執行完成...At The End OF,'+strTime)

print
print ('開始執行方法二 ...')
print


def ClickStart():
    for i in range(1,60):
        print u'正在執行第 ',i,"次 ...",strTime        
    #重新整理瀏覽器
        time.sleep(10)
        driver.refresh()        
        #執行點選事件
    #driver.find_element_by_id("outputButton").click()
        time.sleep(590)
        print
        print u"已執行完第 ",i,"次","共延時",i*600/60,"分"
        print
    
ClickStart()
print

print ('開始工作啦...')
#driver.find_element_by_id("inputButton").click()
print
print ('工作已完成...')

3、QQ_Goto.py

#!-*- coding:utf-8 -*-
from pyvirtualdisplay import Display
from selenium import webdriver
import requests
#要簽到的QQ群號列表
groupid = [123456789,987654321]
headers = {"Content-Type":"application/x-www-form-urlencoded","Host":"qiandao.qun.qq.com","Origin":"http://qiandao.qun.qq.com","Referer": "http://qiandao.qun.qq.com","User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36"}
#建立一個啟動session的請求物件
s = requests.Session()
def login():
        try:
                #啟動一個虛擬桌面
                display = Display(visible=0, size=(1100,700))
                display.start()
                driver = webdriver.Firefox()
                driver.set_window_position(20, 40)
                driver.set_window_size(1100,700)
                #開啟QQ登入介面 準備登入
                driver.get('http://qzone.qq.com')
                driver.switch_to_frame('login_frame')
                driver.find_element_by_id('switcher_plogin').click()
                driver.find_element_by_id('u').clear()
                #填寫QQ帳號
                driver.find_element_by_id('u').send_keys('qq號')
                driver.find_element_by_id('p').clear()
                #填寫QQ密碼
                driver.find_element_by_id('p').send_keys('****zh30.com****')
                #模擬點選登入按鈕 執行登入 獲取cookie
                driver.find_element_by_id('login_button').click()
                cookies = driver.get_cookies()
                #退出瀏覽器
                driver.quit()
                display.stop()
        #return cookies
        except:
                pass

cookies = login()
for cookie in cookies:
        if cookie['name'] == 'skey':
                skey = cookie['value']
        s.cookies.set(cookie['name'], cookie['value'])

#計算bkn並存入cookie
e = 5381
for i in range(len(skey)):
    e = e + (e<<5)+ord(skey[i])
bkn = str(2147483647 & e)
s.cookies.set("Gtk", bkn)
#簽到方法
def sign(groupid):
    for gid in groupid:
        response = s.post("http://qiandao.qun.qq.com/cgi-bin/sign", data={"gc":gid, "is_sign":0, "bkn":bkn}, headers=headers)
        responseJson = response.json()
        if responseJson.has_key('em') and responseJson['em'] == 'no login':
            break
#開始簽到
sign(groupid)