天天看點

[Python爬蟲] Selenium自動通路Firefox和Chrome并實作搜尋截圖

        前兩篇文章介紹了安裝,此篇文章算是一個簡單的進階應用吧!它是在windows下通過selenium+python實作自動通路firefox和chrome并實作搜尋截圖的功能。

自動通路firefox

        可以參照前文安裝selenium環境,目前selenium這個用于web應用程式測試的工具支援的浏覽器包括ie、mozilla firefox、mozilla

suite、chrome等。但是由于firefox是預設安裝路徑,webdriver可以正常通路它,而chrome和ie需要設定driver路徑。

        運作效果如下圖所示,自動調用firefox浏覽器搜尋,同時輸出斷言錯誤:

        assert "谷歌" in driver.title assertionerror

[Python爬蟲] Selenium自動通路Firefox和Chrome并實作搜尋截圖

源碼分析

from selenium import webdriver        from selenium.webdriver.common.keys import keys        import sys

        首先導入selenium.webdriver模闆,它提供了webdriver的實作方法,目前支援這些方法的有firefox、chrome、ie和remote。同時導入keys類,它提供了操作鍵盤的快捷鍵,如reture、f1、alt等。最後導入sys主要是設定編碼方式。

reload(sys)        sys.setdefaultencoding('gb18030') 

        由于漢語中可能會遇到錯誤:

        unicodedecodeerror: 'ascii' codec can't decode byte 0xc4 in position 33

        unicodedecodeerror: 'utf8' codec can't decode byte 0xb0 in position 35

        是以此處轉換成gb編碼,該篇不重點介紹了。

driver = webdriver.firefox()        driver.get("http://www.baidu.com")

        建立firefoxwebdriver執行個體。其中firefox最簡單,其他chrome還需要driver和配置路徑。接下來通過driver.get()打開百度url網頁,webdriver會等待網頁元素加載完成之後才把控制權交回腳本。但是,如果要打開了頁面在加載的過程中包含了很多ajax,webdriver可能無法準确判斷頁面何時加載完成。

assert "百度" in driver.title        assert "谷歌" in driver.title

         接下來使用斷言判斷文章的标題title是否包含“百度”和“谷歌”。對應的标題是“百度一下,你就知道”,是以其中“百度”包括,而“谷歌”會出現斷言報錯。

        同時送出頁面并獲得傳回結果,為了判斷結果是否成功傳回也可以使用斷言。

elem = driver.find_element_by_name("wd")

        webdriver提供了很多如find_element_by_*的方法來比對要查找的元素。如利用name屬性查找方法find_element_by_name來定位輸入框,審查元素name=wd。

[Python爬蟲] Selenium自動通路Firefox和Chrome并實作搜尋截圖
elem.send_keys("eastmount") elem.send_keys(keys.return)

        send_keys方法可以用來模拟鍵盤操作,相當于是在搜尋框中輸入“eastmount”再按Enter鍵搜尋。但首先要從selenium.webdriver.common.keys導入keys類。

driver.save_screenshot('baidu.png') driver.close() driver.quit()

        最後是調用save_screenshot進行截圖,但是圖檔是過程中的,怎樣擷取最後加載的圖檔呢?同時,操作完成并關閉浏覽器。當然,也可以調用quit()方法,兩者的差別在于:quit()方法會退出浏覽器,而close()方法隻是關閉頁面,但如果隻有一個頁面被打開,close()方法同樣會退出浏覽器。

自動通路chrome

        代碼如下:

        需要放置chromedriver如下路徑,同時可以通過代碼設定。但是由于我的chrome可能bug一直未修複,總是打開錯誤。

driver = webdriver.chrome(executable_path="g:\chromedriver.exe")
[Python爬蟲] Selenium自動通路Firefox和Chrome并實作搜尋截圖

參考資料:

        最後希望該篇基礎性文章對你有所幫助吧!如果有不足之處,還請海涵~