您好,登錄后才能下訂單哦!
利用Splinter開發(fā)瀏覽器自動(dòng)化操作,編寫代碼比較簡單。
案例一:
from splinter import Browser with Browser() as browser: # Visit URL url = "http://www.google.com" browser.visit(url) browser.fill('q', 'splinter - python acceptance testing for web applications') # Find and click the 'search' button button = browser.find_by_name('btnG') # Interact with elements button.click() if browser.is_text_present('splinter.readthedocs.io'): print("Yes, the official website was found!") else: print("No, it wasn't found... We need to improve our SEO techniques")
第1行 是導(dǎo)入Browser。
Browser是整個(gè)測試的基礎(chǔ),你可以把它理解為一個(gè)瀏覽器。
第3行 初始化一個(gè)Browser,不加參數(shù)的話默認(rèn)是firefox。
第4行 是命令browser打開"http://google.com"。
第5行 是命令browser使用‘splinter - python acceptance testing for web applications'填充頁面中‘name'是‘q'的元素。在Google的首頁中,就是那個(gè)搜索框。大家可以看一下Google首頁的代碼。
第6行 是兩個(gè)命令。第一個(gè)是找到‘name'屬性為‘btnG'的按鈕,第二個(gè)是click()也就是點(diǎn)擊這個(gè)按鈕。這個(gè)按鈕就是Google的搜索按鈕。
第8行 是判斷頁面中是否有‘splinter.cobrateam.info'這個(gè)字符串,因?yàn)樯弦徊近c(diǎn)擊了搜索按鈕,所以這里搜索的就是跳轉(zhuǎn)之后的頁面。當(dāng)然,大家不用擔(dān)心網(wǎng)速慢會(huì)判斷出錯(cuò),splinter會(huì)等頁面載入完成再進(jìn)行下一步的操作。
第13行 是刪除browser。
案例二:
這里,我給出自動(dòng)登錄126郵箱的案例。難點(diǎn)是要找到頁面的賬戶、密碼、登錄的頁面元素,這里需要查看126郵箱登錄頁面的源碼,才能找到相關(guān)控件的id.
例如:輸入密碼,密碼的文本控件id是pwdInput.可以使用browser.find_by_id()方法定位到密碼的文本框,
接著使用fill()方法,填寫密碼。至于模擬點(diǎn)擊按鈕,也是要先找到按鈕控件的id,然后使用click()方法。
由于代碼較簡單,我就只在代碼中給出注解說明工作原理。
#coding=utf-8 import time from splinter import Browser def splinter(url): browser = Browser('chrome') #login 126 email websize browser.visit(url) #wait web element loading time.sleep(5) #fill in account and password browser.find_by_id('idInput').fill('xxxxxx') browser.find_by_id('pwdInput').fill('xxxxx') #click the button of login browser.find_by_id('loginBtn').click() time.sleep(8) #close the window of brower browser.quit() if __name__ == '__main__': websize3 ='http://www.126.com' splinter(websize3)
以上這篇Python利用splinter實(shí)現(xiàn)瀏覽器自動(dòng)化操作方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。