目的:登录cnblog后新增文章后再次删除该文章并验证
代码如下:
#coding: utf-8
from selenium import webdriver
from time import sleep
import unittest
import time
class DeletePost(unittest.TestCase):
def setUp(self):
self.dr = webdriver.Chrome()
self.dr.maximize_window()
#定义登录方法
def login(self, username, password):
self.dr.get('https://passport.cnblogs.com/user/signin') #cnblog登录页面
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()
#定义新增文章方法
def create_post(self, title, content):
self.dr.get('https://i.cnblogs.com/EditPosts.aspx?opt=1') #cnblog新增文章页面
self.dr.find_element_by_id('Editor_Edit_txbTitle').send_keys(title)
self.set_content(content)
self.dr.find_element_by_id('Editor_Edit_lkbPost').click()
#定义输入富文本content方法
def set_content(self, content):
js = 'document.getElementById("Editor_Edit_EditorBody_ifr").contentWindow.document.body.innerHTML=\'%s\'' % (content)
self.dr.execute_script(js)
#定义获取文章post-id方法
def create_post_and_return_its_id(self, title, content):
self.create_post(title, content) #调用新增文章方法,为后面获取新增后文章的post-id做准备
tokens = self.dr.find_element_by_css_selector('#TipsPanel_LinkEdit').get_attribute('href').split('=')
return tokens[-1] #所有文章都对应唯一的post-id
#验证删除新增的文章
def test_delete_post_success(self):
'''验证删除新增加的Post'''
self.login('kemi_xxxx', 'kemi_xxxx') #cnblog帐号密码
title = 'title %s' %(time.time()) #标题为title加当前时间
content = 'content %s' %(time.time()) #内容为content加当前时间
sleep(5)
post_id = self.create_post_and_return_its_id(title, content) #调用post-id方法并获得相应id
self.dr.get('https://i.cnblogs.com/') #cnblog后台管理页面
row_id = 'post-row-' + post_id #定义文章列表的行id
post = self.dr.find_element_by_id(row_id) #定位到相应行id上
post.find_element_by_xpath("//a[@href='javascript:void(0)']").click() #定位上面选择行上的删除并点击
self.dr.switch_to_alert().accept() #点击弹窗中的确定
sleep(2)
post.find_element_by_xpath("//span[@style='color:red']") #定位相应post的“删除成功!”提示(用来验证删除)
def tearDown(self):
print('测试完毕!')
self.dr.quit()
if __name__ == '__main__':
unittest.main()
效果如下:
转载于:https://blog.51cto.com/kemixing/1886412