用python+selenium登錄cnblog後新增文章後再次刪除該文章並驗證

目的:登錄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()

效果如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章