python+selenium自動化軟體測試(第6章):selenium phantomjs頁面解析使用

來源:互聯網
上載者:User

標籤:sig   html   cut   需要   5.0   code   text   tps   遍曆   

我們都知道Selenium是一個Web的自動化測試載入器,可以在多平台下操作多種瀏覽器進行各種動作,比如運行瀏覽器,訪問頁面,點擊按鈕,提交表單,瀏覽器視窗調整,滑鼠右鍵和拖放動作,下拉框和對話方塊處理等,我們抓取時選用它,主要是Selenium可以渲染頁面,運行頁面中的JS,以及其點擊按鈕,提交表單等操作。

from selenium import webdriverdriver = webdriver.PhantomJS()driver.get("http://www.xxxxxx.com")data = driver.titleprint data

我們為什麼要用phantomjs呢?

介紹

PhantomJS是一個基於webkit的JavaScript API。任何你可以在基於webkit瀏覽器做的事情,它都能做到。它不僅是個隱形的瀏覽器(沒有UI介面的瀏覽器),提供了諸如CSS選取器、支援Web標準、DOM操作、JSON、HTML5、Canvas、SVG等,同時也提供了處理檔案I/O的操作,從而使你可以向作業系統讀寫檔案等。PhantomJS的用處可謂非常廣泛,諸如前端無介面自動化測試(需要結合Jasmin)、網路監測、網頁截屏等。

windows下進行安裝:

pip install selenium

phantomjs使用簡單的使用方式:

from selenium import webdriverbrowser = webdriver.PhantomDS(‘D:\phantomjs.exe‘) #瀏覽器初始化;Win下需要設定phantomjs路徑,linux下置空即可url = ‘http://www.xxxxxx.com‘ # 設定訪問路徑地址browser.get(url) # 開啟網頁title = browser.find_elements_by_xpath(‘xxxxxx‘) #用xpath擷取元素for t in title: # 遍曆輸出  print t.text #輸出其中文本  print t.get_attribute(’class’)# 輸出屬性值browser.qiiit() #關閉瀏覽器。當出現異常時記得在任務瀏覽器中關閉

我們進行一個簡單的對比操作,首先請回顧一下selenium webdriver的操作

from selenium import webdriverdriver = webdriver.Firefox()driver.get("https: //www.xxxxxx.com/")dniver.find_element_by_id(‘xxxxxxxx‘).send_keys("nxxxxxx")dniver.find_element_by_id("xxxxxxxx").click()driver.quit()

使用phantomjs

from selenium import webdriverdriver = webdriver.PhantomJS()driver.set_window_size(xxx,xxx) #瀏覽器大小driver.get ("https: //www.xxx.com/")dniver.find_element_by_id(‘xxxx‘).send_keys("xxxx")dniver.find_element_by_id("xxxxxx").click()print driver.current_urldriver.quit()

通過以上兩個案例大家應該可以看出相關的一個區別所在!!
編寫一個簡單的斷言來判斷phantomjs擷取得到的URL是否正確的呢:

import unittestfrom selenium import webdriverclass TestOne(unittest.TestCase):    def setUp(self):        self.driver = webdniver.PhantomDS()        self.driver.set_window_size(xxx, xxx)    def test_url(self):        self.driver.get("https://www.xxx.com")        self.driver.find_element_by_id(‘xxxxxx‘).send_keys("xxxx")        self.driver.find_element_by_id("xxxxx").click()        self.assentln("https://www.xxx.com", self.driver.current_url)    def tearDown(self):        self.driver.quit()if __name__ == "__main__":    unittest.main()                  

那麼你會發現通過以上的單元測試進行斷言後是完全可以通過的。
使用PhantomJS在瀏覽器的一個主要優點是測試通常要快得多。

import unittestfrom selenium import webdriverimport timeclass TestThree(unittest.TestCase):  def setUp(self):    self.startTime = time.time()  def test_unl_fire(self):    time.sleep(2)    self.driver = webdniver.Firefox()    self.driver.get("https://www.xxx.com")    button = self.driver.find_element_by_id("xxx").get_attribute("xxxx")    self.assentEquals(‘xxxxx‘, button)  def test_unl_phantom(self):    time.sleep(l)    self.driver = webdniver.PhantomDS()    self.driver.get("https://www.xxx.com")    button = self.driver.find_element_by_id("xxxx").get_attribute("xxxx")    self.assentEquals(‘xxxxx‘, button)  def tearDown(self):    t = time.time() - self.startTime            print "%s: %.3f"% (self.id(), t)            self.driver.quit()if __name__== ‘__main__‘:    suite = unittest.TestLoader().loadTestsFromTestCase(TestThree)    unittest.TextTestRunner(verbosity=0).run(suite)                

 

通過兩個時間上的一個對比你會發現使用phantomjs速度有多快
內容拓展:

# coding:utf-8from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.uiimport WebDriverWaitfrom selenium.webdriver.supportimport expected_conditions as ecimport nose.tools as nose#帳戶email = ‘user‘password = ‘password‘# phantomjs# user agentuser_agent = ‘Mozilla/5.0 (Windows NT 5.1)AppleWebKit/537.36 (KHTML, like Gecko)Chrome/29.0.1547.66 Safari/537.36‘# PhantomUS的路徑pjs_path = ‘xx/node_modules/phantomjs/bin/phantomjsdcap = {"phantomjs.page.settings.userAgent":user_agent,‘marionette‘ : True}driver = webdriver.PhantomJS(executable_path=pjs_path,desired_capabilities=dcap)# 5秒wait = WebDriverWait(driver, 5)#擷取html登入頁面login_page_url = ‘http://xxx‘driver.get(login_page_url)#等到頁面載入wait.until(ec.presence_of_all_elements_located)#檢查當前網址nose.eq_(‘http://xxx‘, driver.current_url)# login# button clickshow_signin = driver.find_element_by_id(‘xxx‘)show_signin.click()# emaillogin_xpath = ‘xxx"]‘#等待對象元素wait.until(ec.visibility_of_element_located((By.XPATH, login_xpath)))login_id_form =driver.find_element_by_xpath(login_xpath)login_id_form.clean()login_id_form.send_keys(email)# passwordpassword_xpath = ‘xxxx‘#等待對象元素wait.until(ec.visibility_of_element_located((By.XPATH, password_xpath)))# passwordpassword_form = driver.find_element_by_xpath(passwond_xpath)password_form.clean()password_form.send_keys(password)# submitsubmit_xpath = ‘xxxx‘dniver.find_element_by_xpath(submit_xpath).click()# resultdriver.get(‘http://xxx‘)#等到頁面載入wait.until(ec.presence_of_all_elements_located)#檢查當前網址nose.eq_(‘http://xxx‘, driver.current_url)user_email = driver.find_element_by_xpath(‘xxx‘).get_attribute("XXX")nose.eq_(email, user_email)

 

python+selenium自動化軟體測試(第6章):selenium phantomjs頁面解析使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.