1. 程式人生 > >selenium:結合httpwatch進行網頁測試(Python版)

selenium:結合httpwatch進行網頁測試(Python版)

【概述】

Httpwatch 一款強大的網頁資料分析工具。它可以捕捉http/https資料,檢視底層的資料,包括headers、cookies、cache等。同時,記錄傳送請求、接收請的時間。Anyway,a good tool for you。
或許,你有一個需求,要在selenium進行頁面功能測試的時候,你需要獲取一些資訊,如提交請求資料、接收請求資料、頁面載入的時間等。selenium + httpwatch,將是一個不錯的解決方案。本文主要介紹,將httpwatch附加到selenium webdriver的方法

【selenium + httpwatch】

官方做法(JAVA版):

IWebDriver driver = <Create Selenium Driver using existing profile>; // Don't use new FirefoxDriver()

// Set a unique initial page title so that HttpWatch can attach to it
string uniqueTitle = Guid.NewGuid().ToString();
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("document.title = '"
+ uniqueTitle + "';"); // Attach HttpWatch to the instance of the browser created through Selenium Plugin plugin = control.AttachByTitle(uniqueTitle);

我就照模照樣的寫個Python版的

control = win32com.client.Dispatch('HttpWatch.Controller')
#driver=webdriver.Ie(executable_path="D:\\software\\IEDriverServer_Win32_2.28.0\\IEDriverServer.exe")
profile = webdriver.FirefoxProfile(r'C:\Users\X230\AppData\Roaming\Mozilla\Firefox\Profiles\68zb9g9a.default') driver=webdriver.Firefox(firefox_profile=profile) uniqueTitle = str(uuid.uuid4()) driver.get(url) driver.execute_script('document.title = "' + uniqueTitle + '";') plugin = control.AttachByTitle(uniqueTitle) plugin.Log.EnableFilter(False) plugin.Record() #plugin.GotoURL(url) plugin.Stop()

請留意官方版的第一句話(如下)。意思是,(如果使用Firefox)請不要使用預設的profile配置,需要使用Firefox本地profile配置。

IWebDriver driver = < Create Selenium Driver using existing profile >; // Don’t use new FirefoxDriver()

selenium Firefox 預設配置檔案是webdriver_prefs.json,預設不載入所有的外掛(add-ons)。所以,如果你忽略第一句,將發生以下報錯:

    plugin = self._control.AttachByTitle(uniqueTitle)
  File "<COMObject HttpWatch.Controller>", line 2, in AttachByTitle
pywintypes.com_error: (-2147352567, '\xb7\xa2\xc9\xfa\xd2\xe2\xcd\xe2\xa1\xa3', (0, u'HttpWatch.Controller', u"AttachByTitle failed because no IE or Firefox page was found with the title 'd9f5f540-3227-4d8a-b928-daaf196e256b'. \r\n\r\nPlease check that HttpWatch is installed, enabled and working correctly in the target browser window. Also if you are using Selenium and Firefox make sure that you are using a copy of a profile that has HttpWatch enabled rather than a fresh profile created by 'new FirefoxDriver()'. For more information please refer to the Selenium/Firefox sample described in the HttpWatch Automation help - AttachByTitle failed", None, 0, -2147467259), None)

那Firefox本地profile檔案在哪,請查閱Firefox官方幫助:

然後,如下初始化driver即可:

driver=webdriver.Firefox(firefox_profile=profile)