Python + Selenium 自動發佈文章(一):開源中國

寫在開始

  還是說說出這個系列的起因吧。之前寫完或是修改了Markdown文章,我還分別需要在多個平臺進行發佈或是更新維護這些內容,這些平臺目前包括我的博客簡書開源中國CSDN,其實早就想過用比較自動化的形式來解決,無奈有技術、時間、精力等各方面原因的限制。廢話不多說吧,直奔今天的主題,本文主要介紹如何用PythonSelenium寫(發)開源中國的博客。

準備說明

  • 一定的Python基礎知識
  • 一定的Selenium相關知識
  • 開發環境說明:Python v3.6.4,Selenium v3.8.1

PS:Selenium操縱瀏覽器是依賴於瀏覽器驅動程序的,下面貼出的是谷歌和火狐瀏覽器驅動程序的下載地址。

Chrome ( chromedriver )

Firefox ( geckodriver )

官方下載

官方下載

淘寶鏡像

淘寶鏡像

備用下載

備用下載

使用說明

  下面是示例代碼中用到的auto.md文件內容,自動發佈文章也還是需要遵循一定的規則,所以以下有幾點是必須說明的: 1. [//]: # ()是Markdown註釋的一種寫法,註釋內容寫在小括號內;   1.< !-- -->是HTML註釋的一種寫法,由於Markdown寫法的註釋有兼容性問題,所以在此調整一下(注意<!之間實際上是沒有空格的,又是爲了兼容某些平臺的Markdown識別,好想o(╥﹏╥)o);   2. auto.md中間註釋部分的內容,用於匹配獲得這幾個平臺的分類和標籤等信息;   3. -->\n僅用於劃分並匹配獲取正文部分內容。

---
title: 自動發佈測試文章
date: 2018-05-16
categories:
    - 測試
author: Jared Qiu
tags:
    - 標籤
cover_picture: https://images.unsplash.com/photo-1520095972714-909e91b038e5?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=1110ecf3ce9e4184d4676c54dec0032d&auto=format&fit=crop&w=500&q=60
top: 1
---

<!--
    self_category: 開源
    self_tags: 博客,docker
    osChina_sys_category: 其他類型
    csdn_article_category: 原創
    csdn_blog_category: 編程語言
-->

### 自動發佈

&emsp;&emsp;自動發佈文章。。

### 參考地址

> [happyJared - 博客](https://blog.mariojd.cn/)

  下面的截圖是開源中國撰寫博客的界面(記得設置默認編輯器爲Markdown)。

write-blog-oschia

  從上圖可以看到,在開源中國寫一篇博客,需要依次錄入標題、摘要(可選)、內容、標籤(可選)和選擇分類(自定義的)、系統分類等信息。   結合auto.md的內容進行分析,相信用過hexo的朋友都比較清楚,標題一般定義在title處;摘要因爲是可選的,所以這裏先忽略不處理;正文內容我們通過匹配-->\n就可以獲取。剩下標籤,自定義分類和系統分類,按規則需要提前定義在註釋裏,分別對應self_tags,self_categoryosChina_sys_category

代碼說明

  main.py:程序入口類,主要負責正則匹配解析Markdown和調用post發佈文章

import re
import oschina
import linecache


class Main(object):
    # init
    def __init__(self, file):
        self.title = ''
        self.content = ''
        self.category = ''
        self.tags = ''
        # OsChina的系統分類, 設個默認值
        self.osChina_sys_category = '編程語言'
        # CSDN的文章分類, 設個默認值
        self.csdn_article_category = '原創'
        # CSDN的博客分類, 設個默認值
        self.csdn_blog_category = '後端'
        self.read_file(file)

    # 讀取MD中的title, content, self_category, self_tags, osChina_sys_category, csdn_article_category, csdn_blog_category
    def read_file(self, markdown_file):
        self.title = linecache.getline(markdown_file, 2).split('title: ')[1].strip('\n')
        with open(markdown_file, 'r', encoding='UTF-8') as f:
            self.content = f.read().split('-->\n')[1]
            # 重置文件指針偏移量
            f.seek(0)
            for line in f.readlines():
                if re.search('self_category: ', line) is not None:
                    self.category = line.split('self_category: ')[1].strip('\n')
                elif re.search('self_tags: ', line) is not None:
                    self.tags = line.split('self_tags: ')[1].strip('\n')
                elif re.search('osChina_sys_category: ', line) is not None:
                    self.osChina_sys_category = line.split('osChina_sys_category: ')[1].strip('\n')
                elif re.search('csdn_article_category: ', line) is not None:
                    self.csdn_article_category = line.split('csdn_article_category: ')[1].strip('\n')
                elif re.search('csdn_blog_category: ', line) is not None:
                    self.csdn_blog_category = line.split('csdn_blog_category: ')[1].strip('\n')


if __name__ == '__main__':
    md_file = 'auto.md'
    print("Markdown File is ", md_file)

    timeout = 10
    main = Main(md_file)

    # 開源中國
    osChina = oschina.OsChina()
    osChina.post(main, timeout)

  authorize.py:目前僅實現了用qq進行授權登錄的方法

from selenium.webdriver.support.wait import WebDriverWait


# QQ授權登錄, 使用前提是QQ客戶端在線
def qq(driver, timeout):
    # 切換到最新打開的窗口
    window_handles = driver.window_handles
    driver.switch_to.window(window_handles[-1])

    print('qq authorize title is ', driver.title)

    # 切換iframe
    iframe = WebDriverWait(driver, timeout).until(lambda d: d.find_element_by_id('ptlogin_iframe'))
    driver.switch_to.frame(iframe)

    # 點擊頭像進行授權登錄
    login = WebDriverWait(driver, timeout).until(lambda d: d.find_element_by_xpath('//*[@id="qlogin_list"]/a[1]'))
    login.click()

  oschina.py:這個是開源中國自動寫(發)博客的核心類

import authorize
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains


# 開源中國
class OsChina(object):
    @staticmethod
    def post(main, timeout):
        # 1.賬號密碼
        account = 'xxx'
        password = 'xxx'

        # 2.跳轉登陸
        login = 'https://www.oschina.net/home/login'
        driver = webdriver.Chrome()
        driver.get(login)

        # 3.窗口最大化
        driver.maximize_window()

        # 4.使用QQ授權登錄
        driver.find_element_by_xpath('/html/body/section/div/div[2]/div[2]/div/div[2]/a[4]').click()
        authorize.qq(driver, timeout)

        # 4.使用賬號密碼登陸
        # driver.find_element_by_id('userMail').send_keys(account)
        # driver.find_element_by_id('userPassword').send_keys(password)
        # driver.find_element_by_xpath('//*[@id="account_login"]/form/div/div[5]/button').click()

        # 5.移到"我的空間", 點擊"我的博客"
        my_space = WebDriverWait(driver, timeout).until(lambda d: d.find_element_by_xpath('//*[@id="MySpace"]'))
        ActionChains(driver).move_to_element(my_space).perform()
        driver.find_element_by_xpath('/html/body/header/div/div[2]/div/div[2]/div/ul/li[4]/a').click()

        # 6.點擊"寫博客"
        write_blog = WebDriverWait(driver, timeout).until(
            lambda d: d.find_element_by_xpath('/html/body/div/div/div/div/div[1]/div[1]/div[4]/a'))
        write_blog.click()

        # 7.選擇自定義分類, 系統分類
        classify = WebDriverWait(driver, timeout).until(lambda d: d.find_elements_by_class_name('select-opt'))
        for c in classify:
            html = c.get_attribute('innerHTML')
            if main.category in html:
                if 'span' in html:
                    # 自定義分類
                    data_value = c.get_attribute('data-value')
                    js = 'document.getElementById("self_sort").value=' + data_value
                    driver.execute_script(js)
            else:
                if main.osChina_sys_category == html:
                    # 系統分類
                    data_value = c.get_attribute('data-value')
                    js = 'document.getElementById("sys_sort").value=' + data_value
                    driver.execute_script(js)

        # 8.填寫標題, 內容和標籤
        title = driver.find_element_by_xpath('//*[@id="title"]')
        title.clear()
        title.send_keys(main.title)
        content = driver.find_element_by_id('mdeditor')
        content.clear()
        content.send_keys(main.content)
        tags = driver.find_element_by_xpath('//*[@id="blog-form"]/div[2]/div/div[3]/div[1]/div[2]/div[2]/input')
        tags.clear()
        tags.send_keys(main.tags)

        # 9.保存草稿
        driver.find_element_by_xpath('//*[@id="blog-form"]/div[3]/div/button[1]').click()
        # 9.發佈文章
        # driver.find_element_by_xpath('//*[@id="blog-form"]/div[3]/div/button[2]').click()

  從代碼註釋可以看到,目前支持賬號密碼和QQ授權兩種方式登錄,支持保存草稿或發佈文章操作。

運行效果

  多說無益,來看看運行效果圖吧,測試一下保存草稿。

auto-post-oschia

寫在最後

  總之,在開源中國自動寫文章的思路大概就這樣,不過這也絕對不是唯一的辦法,大家完全可以根據代碼自己做調整,而且網頁的結構可能會發生改變,這裏也不敢保證程序可以一直正常運行下去。好了,下一篇介紹如何在簡書自動寫(發)文章。

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