目的:使用pyhton下的unittest單元測試框架並結合selenium的webdriver來實現將騰訊首頁的今日話題下的內容自動發表達到自己的cnblog裏。
思路:創建QQDailyTopic類繼承unittest的TestCase類,setUp()方法用於測試執行前的初始化工作,而最後的tearDown()與setUp()方法相呼應,用於測試執行之後的善後工作。
然後用方法get_qq_daily_topic_url獲得qq首頁今日話題的url;
方法get_title_and_content_from_qq_daily_topic從今日話題獲得後面我們在cnblog下新blog需要的標題title和富文本content,提取今日話題title文本和內容的innerHTML;
方法login用於登錄,定位元素並輸入username和password然後點擊登錄按鈕;
方法set_content用於向富文本框填入內容,這裏藉助js向添加新隨筆的富文本框插入指定內容,通過scecute_scrit()執行js代碼;
方法test_transpond_qq_daily_topic用來測試向cnblog裏轉發qq首頁今日話題,包括自動用有效用戶名和密碼登錄我的博客,在添加新隨筆的標題和富文本框裏自動填入今日話題的標題和內容,最後點擊發布按鈕。unittest下必須以“test”開頭的方法。
實現代碼如下:
#coding=utf-8 from selenium import webdriver import unittest from time import sleep class QQDailyTopic(unittest.TestCase): def setUp(self): self.dr = webdriver.Firefox() self.title, self.content = self.get_title_and_content_from_qq_daily_topic() def get_qq_daily_topic_url(self): return self.dr.find_element_by_css_selector('#todaytop a').get_attribute('href') def get_title_and_content_from_qq_daily_topic(self): self.dr.get('http://www.qq.com/') url = self.get_qq_daily_topic_url() self.dr.get(url) title = self.dr.find_element_by_id('sharetitle').text content = self.dr.find_element_by_id('articleContent').get_attribute('innerHTML') return (title, content) def login(self, username, password): self.dr.find_element_by_id('input1').send_keys(username) self.dr.find_element_by_id('input2').send_keys(password) self.dr.find_element_by_id('signin').click() #藉助js向添加新隨筆的富文本框插入指定內容 def set_content(self, text): text = text.strip() js = 'document.getElementById("Editor_Edit_EditorBody_ifr").contentWindow.document.body.innerHTML=\'%s\'' %(text) print(js) self.dr.execute_script(js) def test_transpond_qq_daily_topic(self): self.dr.get('https://passport.cnblogs.com/user/signin') self.login('kemi_xxxx', 'kemi_xxxx')#自己博客園用戶名和密碼 sleep(3) self.dr.get('https://i.cnblogs.com/EditPosts.aspx?opt=1') self.dr.find_element_by_id('Editor_Edit_txbTitle').send_keys(self.title) self.set_content(self.content) self.dr.find_element_by_id('Editor_Edit_lkbPost').click() def tearDown(self): sleep(5) self.dr.quit() if __name__ == '__main__': unittest.main()
實現效果如下:
QQ首頁的今日話題
cnblog轉發今日話題
部分內容截圖