1. 程式人生 > 程式設計 >獲取CSDN文章內容並轉換為markdown文字的python

獲取CSDN文章內容並轉換為markdown文字的python

自己寫的小工具,可以直接獲取csdn文章並轉換為markdown格式

效果圖

獲取CSDN文章內容並轉換為markdown文字的python

核心程式碼

from PySide2.QtWidgets import QApplication,QMainWindow,QPushButton,QPlainTextEdit,QMessageBox
import re
import parsel
import tomd
import requests
class CSDN():
  def __init__(self):
    self.windows = QMainWindow()
    self.windows.resize(450,300)
    self.windows.setWindowTitle("輕鬆獲取csdn文章--by tansty")
    self.setup_ui()
    self.set_connect()
  def set_connect(self):
    #設定建立聯絡
    self.button.clicked.connect(self.spider_csdn)
  def setup_ui(self):
    #設定ui介面的建立
    self.button = QPushButton(self.windows)
    self.button.resize(100,100)
    self.button.move(150,150)
    self.button.setText("獲取文章")
    self.text = QPlainTextEdit(self.windows)
    self.text.setPlaceholderText("請輸入需要獲取文章的連結")
    self.text.resize(450,100)
  def spider_csdn(self):
    # 目標文章的連結
    title_url=self.text.toPlainText()
    MessageBox = QMessageBox(self.windows)
    if not title_url:
      MessageBox.critical(self.windows,"錯誤","請輸入網址")
      return
    head={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.52"
    }
    html=requests.get(url=title_url,headers=head).text
    page=parsel.Selector(html)
    #建立直譯器
    title=page.css(".title-article::text").get()
    res = re.compile("[^\u4e00-\u9fa5^a-z^A-Z^0-9]")
    restr = ''
    res.sub(restr,title)
    content=page.css("article").get()
    content=re.sub("<a.*?a>","",content)
    content = re.sub("<br>",content)
    texts=tomd.Tomd(content).markdown
    #轉換為markdown 檔案
    with open(title+".md",mode="w",encoding="utf-8") as f:
      f.write("#"+title)
      f.write(texts)
      MessageBox.information(self.windows,"正確","獲取文章完成")
if __name__ == '__main__':
  app = QApplication()
  csdn=CSDN()
  csdn.windows.show()
  app.exec_()

檔案打包下載 連結: https://pan.baidu.com/s/1R6RcrDagwf1vWzmRCBja4w 提取碼: ug6n