目的:使用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转发今日话题
部分内容截图
转载于:https://blog.51cto.com/kemixing/1887550