Technology Sharing

Python function production to obtain the corresponding data of all published articles on CSDN

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Hello everyone, today I want to share a practicalPython Script, which can help you batch obtain the relevant data of all published articles on the CSDN blog and save the data into an Excel file. In addition, the script will obtain a quality score for each article and record this score in Excel as well. Let's get started!

Script functionality overview

This script is mainly divided into two parts:

  1. Get article information and save to Excel:This part will get your article list from CSDN API and save the key information into an Excel file.
  2. Get article quality score and update Excel: This part will request a quality score for each article and add the score to the corresponding Excel file.

Implementation steps

1. Import necessary libraries

First, we need to import some Python libraries to help us with this task:

  1. import json
  2. import pandas as pd
  3. from openpyxl import Workbook, load_workbook
  4. from openpyxl.utils.dataframe import dataframe_to_rows
  5. import math
  6. import requests

2. Define and save article informationExcelthe type

We defined a classGetInformationToExcelTo handle the acquisition of article information and the saving of Excel files:

  1. class GetInformationToExcel:
  2. def __init__(self, username, cookies, Referer, page, size, filename):
  3. self.username = username
  4. self.cookies = cookies
  5. self.Referer = Referer
  6. self.size = size
  7. self.filename = filename
  8. self.page = page
  9. # 发送HTTP GET请求到CSDN的API,获取文章列表
  10. def get_articles(self):
  11. url = "https://blog.csdn.net/community/home-api/v1/get-business-list"
  12. params = {
  13. "page": {self.page},
  14. "size": {self.size},
  15. "businessType": "blog",
  16. "username": {self.username}
  17. }
  18. headers = {
  19. 'User-Agent': 'Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
  20. 'Cookie': self.cookies,
  21. 'Referer': self.Referer
  22. }
  23. try:
  24. response = requests.get(url, params=params, headers=headers)
  25. response.raise_for_status()
  26. data = response.json()
  27. return data.get('data', {}).get('list', [])
  28. except requests.exceptions.HTTPError as e:
  29. print(f"HTTP错误: {e.response.status_code} {e.response.reason}")
  30. except requests.exceptions.RequestException as e:
  31. print(f"请求异常: {e}")
  32. except json.JSONDecodeError:
  33. print("解析JSON失败")
  34. return []
  35. # 将文章列表转换为Pandas DataFrame,选择并重命名必要的列。
  36. def export_to_excel(self):
  37. df = pd.DataFrame(self.get_articles())
  38. df = df[['title', 'url', 'postTime', 'viewCount', 'collectCount', 'diggCount', 'commentCount']]
  39. df.columns = ['文章标题', 'URL', '发布时间', '阅读量', '收藏量', '点赞量', '评论量']
  40. wb = Workbook()
  41. sheet = wb.active
  42. for r in dataframe_to_rows(df, index=False, header=True):
  43. sheet.append(r)
  44. for column in sheet.columns:
  45. max_length = 0
  46. column = [cell for cell in column]
  47. for cell in column:
  48. try:
  49. if len(str(cell.value)) > max_length:
  50. max_length = len(cell.value)
  51. except:
  52. pass
  53. adjusted_width = (max_length + 5)
  54. sheet.column_dimensions[column[0].column_letter].width = adjusted_width
  55. # Save the workbook
  56. wb.save(self.filename)

In this class, we implemented the following methods:

  • __init__: Initialization method, setting the basic properties of the class.
  • get_articles: Send an HTTP GET request to the CSDN API to get a list of articles.
  • export_to_excel: Convert the article list to a Pandas DataFrame and save it to an Excel file.

3. Define the class for obtaining article quality scores

Next, we define another classGetArticleScoresTo handle the acquisition of article quality scores and the update of Excel files:

  1. class GetArticleScores:
  2. def __init__(self, filepath):
  3. self.filepath = filepath
  4. # 发送HTTP POST请求到一个API,获取文章的质量分。
  5. @staticmethod
  6. def get_article_score(article_url):
  7. url = "https://bizapi.csdn.net/trends/api/v1/get-article-score"
  8. headers = {
  9. "Accept": "application/json, text/plain, */*",
  10. "X-Ca-Key": "203930474",
  11. "X-Ca-Nonce": "b35e1821-05c2-458d-adae-3b720bb15fdf",
  12. "X-Ca-Signature": "gjeSiKTRCh8aDv0UwThIVRITc/JtGJkgkZoLVeA6sWo=",
  13. "X-Ca-Signature-Headers": "x-ca-key,x-ca-nonce",
  14. "X-Ca-Signed-Content-Type": "multipart/form-data",
  15. }
  16. data = {"url": article_url}
  17. try:
  18. response = requests.post(url, headers=headers, data=data)
  19. response.raise_for_status() # This will raise an error for bad responses
  20. return response.json().get('data', {}).get('score', 'Score not found')
  21. except requests.RequestException as e:
  22. print(f"Request failed: {e}")
  23. return "Error fetching score"
  24. def get_scores_from_excel(self):
  25. """读取Excel文件,获取文章URL列表。
  26. 对每个URL调用 get_article_score 方法,获取分数列表。
  27. 返回分数列表。"""
  28. df = pd.read_excel(self.filepath)
  29. urls = df['URL'].tolist()
  30. scores = [self.get_article_score(url) for url in urls]
  31. return scores
  32. def write_scores_to_excel(self):
  33. """读取Excel文件到DataFrame。
  34. 将获取的分数添加到DataFrame中。
  35. 将更新后的DataFrame保存回Excel文件。"""
  36. df = pd.read_excel(self.filepath)
  37. df['质量分'] = self.get_scores_from_excel()
  38. df.to_excel(self.filepath, index=False)

In this class, we implemented the following methods:

  • __init__: Initialization method, setting the basic properties of the class.
  • get_article_score: Static method that sends an HTTP POST request to an API to obtain the quality score of the article.
  • get_scores_from_excel: Read the Excel file, get the article URL list, and get the score list.
  • write_scores_to_excel: Read the Excel file into a DataFrame, add the obtained scores to the DataFrame, and save it back to the Excel file.

4. Main program

Finally, we set the total number of articles, cookies, Referer, and CSDN user ID in the main program and performed the following steps:

  • Calculate the number of pages that need to be requested.
  • Loop through each page of articles, create an Excel file, and get the quality score and write it into Excel.
  1. if __name__ == '__main__':
  2. # 请填写:已发文章总数量,cookies,你的首页Referer,你的id:CSDNid
  3. total = 145
  4. cookies = 'uuid_tt_dd=10' # Simplified for brevity
  5. Referer = 'https://blog.csdn.net/q244645787'
  6. CSDNid = 'q244645787'
  7. # 下面是计算和获取
  8. t_index = math.ceil(total / 100) + 1 # 向上取整,半闭半开区间,开区间+1。
  9. for index in range(1, t_index): # 文章总数
  10. filename = "score" + str(index) + ".xlsx"
  11. exporter_excel = GetInformationToExcel(CSDNid, cookies, Referer, index, 100, filename) # Replace with your username
  12. exporter_excel.export_to_excel()
  13. article_score = GetArticleScores(filename)
  14. article_score.write_scores_to_excel()
  15. print("获取完成")

After the execution is completed, you will get an Excel file containing all article data and quality scores.

All code:

  1. import json
  2. import pandas as pd
  3. from openpyxl import Workbook, load_workbook
  4. from openpyxl.utils.dataframe import dataframe_to_rows
  5. import math
  6. import requests
  7. # 批量获取文章信息并保存到excel
  8. class GetInformationToExcel:
  9. def __init__(self, username, cookies, Referer, page, size, filename):
  10. self.username = username
  11. self.cookies = cookies
  12. self.Referer = Referer
  13. self.size = size
  14. self.filename = filename
  15. self.page = page
  16. # 发送HTTP GET请求到CSDN的API,获取文章列表
  17. def get_articles(self):
  18. url = "https://blog.csdn.net/community/home-api/v1/get-business-list"
  19. params = {
  20. "page": {self.page},
  21. "size": {self.size},
  22. "businessType": "blog",
  23. "username": {self.username}
  24. }
  25. headers = {
  26. 'User-Agent': 'Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
  27. 'Cookie': self.cookies,
  28. 'Referer': self.Referer
  29. }
  30. try:
  31. response = requests.get(url, params=params, headers=headers)
  32. response.raise_for_status()
  33. data = response.json()
  34. return data.get('data', {}).get('list', [])
  35. except requests.exceptions.HTTPError as e:
  36. print(f"HTTP错误: {e.response.status_code} {e.response.reason}")
  37. except requests.exceptions.RequestException as e:
  38. print(f"请求异常: {e}")
  39. except json.JSONDecodeError:
  40. print("解析JSON失败")
  41. return []
  42. # 将文章列表转换为Pandas DataFrame,选择并重命名必要的列。
  43. def export_to_excel(self):
  44. df = pd.DataFrame(self.get_articles())
  45. df = df[['title', 'url', 'postTime', 'viewCount', 'collectCount', 'diggCount', 'commentCount']]
  46. df.columns = ['文章标题', 'URL', '发布时间', '阅读量', '收藏量', '点赞量', '评论量']
  47. wb = Workbook()
  48. sheet = wb.active
  49. for r in dataframe_to_rows(df, index=False, header=True):
  50. sheet.append(r)
  51. for column in sheet.columns:
  52. max_length = 0
  53. column = [cell for cell in column]
  54. for cell in column:
  55. try:
  56. if len(str(cell.value)) > max_length:
  57. max_length = len(cell.value)
  58. except:
  59. pass
  60. adjusted_width = (max_length + 5)
  61. sheet.column_dimensions[column[0].column_letter].width = adjusted_width
  62. # Save the workbook
  63. wb.save(self.filename)
  64. # 获取每篇文章的质量分,并将分数写入到Excel文件中
  65. class GetArticleScores:
  66. def __init__(self, filepath):
  67. self.filepath = filepath
  68. # 发送HTTP POST请求到一个API,获取文章的质量分。
  69. @staticmethod
  70. def get_article_score(article_url):
  71. url = "https://bizapi.csdn.net/trends/api/v1/get-article-score"
  72. headers = {
  73. "Accept": "application/json, text/plain, */*",
  74. "X-Ca-Key": "203930474",
  75. "X-Ca-Nonce": "b35e1821-05c2-458d-adae-3b720bb15fdf",
  76. "X-Ca-Signature": "gjeSiKTRCh8aDv0UwThIVRITc/JtGJkgkZoLVeA6sWo=",
  77. "X-Ca-Signature-Headers": "x-ca-key,x-ca-nonce",
  78. "X-Ca-Signed-Content-Type": "multipart/form-data",
  79. }
  80. data = {"url": article_url}
  81. try:
  82. response = requests.post(url, headers=headers, data=data)
  83. response.raise_for_status() # This will raise an error for bad responses
  84. return response.json().get('data', {}).get('score', 'Score not found')
  85. except requests.RequestException as e:
  86. print(f"Request failed: {e}")
  87. return "Error fetching score"
  88. def get_scores_from_excel(self):
  89. """读取Excel文件,获取文章URL列表。
  90. 对每个URL调用 get_article_score 方法,获取分数列表。
  91. 返回分数列表。"""
  92. df = pd.read_excel(self.filepath)
  93. urls = df['URL'].tolist()
  94. scores = [self.get_article_score(url) for url in urls]
  95. return scores
  96. def write_scores_to_excel(self):
  97. """读取Excel文件到DataFrame。
  98. 将获取的分数添加到DataFrame中。
  99. 将更新后的DataFrame保存回Excel文件。"""
  100. df = pd.read_excel(self.filepath)
  101. df['质量分'] = self.get_scores_from_excel()
  102. df.to_excel(self.filepath, index=False)
  103. if __name__ == '__main__':
  104. # 请填写:已发文章总数量,cookies,你的首页Referer,你的id:CSDNid
  105. total = 145
  106. cookies = 'uuid_tt_dd=10' # Simplified for brevity
  107. Referer = 'https://blog.csdn.net/q244645787'
  108. CSDNid = 'q244645787'
  109. # 下面是计算和获取
  110. t_index = math.ceil(total / 100) + 1 # 向上取整,半闭半开区间,开区间+1。
  111. for index in range(1, t_index): # 文章总数
  112. filename = "score" + str(index) + ".xlsx"
  113. exporter_excel = GetInformationToExcel(CSDNid, cookies, Referer, index, 100, filename) # Replace with your username
  114. exporter_excel.export_to_excel()
  115. article_score = GetArticleScores(filename)
  116. article_score.write_scores_to_excel()
  117. print("获取完成")

Effect