Compartilhamento de tecnologia

Produção de funções Python para obter os dados correspondentes de todos os artigos publicados na CSDN

2024-07-12

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

Olá a todos, hoje quero compartilhar uma práticaScript Python , pode ajudá-lo a obter dados relevantes de todos os artigos publicados no blog CSDN em lotes e salvar os dados em um arquivo Excel. Além disso, o script obtém uma pontuação de qualidade para cada artigo e também registra essa pontuação no Excel. vamos começar!

Visão geral da funcionalidade do script

Este script é dividido principalmente em duas partes:

  1. Obtenha informações do artigo e salve no Excel: Esta parte obterá sua lista de artigos da API CSDN e salvará as principais informações em um arquivo Excel.
  2. Obtenha o índice de qualidade do artigo e atualize o Excel: Esta parte solicitará uma pontuação de qualidade para cada artigo e adicionará essa pontuação ao arquivo Excel correspondente.

Etapas de implementação

1. Importe as bibliotecas necessárias

Primeiro, precisamos importar algumas bibliotecas Python para nos ajudar a realizar esta tarefa:

  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. Defina para obter informações do artigo e salve-as emExcelo tipo

Definimos uma classeGetInformationToExcelPara obter informações do artigo e salvar arquivos Excel:

  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)

Nesta classe, implementamos os seguintes métodos:

  • __init__: Método de inicialização para definir os atributos básicos da classe.
  • get_articles: envie uma solicitação HTTP GET para a API CSDN para obter a lista de artigos.
  • export_to_excel: converta a lista de artigos em um DataFrame do Pandas e salve-a em um arquivo Excel.

3. Defina as categorias para obtenção dos índices de qualidade dos artigos

A seguir, definimos outra classeGetArticleScoresPara lidar com a aquisição de índices de qualidade de artigos e atualização de arquivos Excel:

  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)

Nesta classe, implementamos os seguintes métodos:

  • __init__: Método de inicialização para definir os atributos básicos da classe.
  • get_article_score: Método estático, envia solicitação HTTP POST para uma API para obter o índice de qualidade do artigo.
  • get_scores_from_excel: Leia o arquivo Excel, obtenha a lista de URLs do artigo e a lista de pontuações.
  • write_scores_to_excel: Leia o arquivo Excel no DataFrame, adicione as pontuações obtidas ao DataFrame e salve-o novamente no arquivo Excel.

4. Programa principal

Por fim, definimos o número total de artigos, cookies, Referer e ID de usuário CSDN no programa principal e executamos as seguintes etapas:

  • Calcule o número de páginas que precisam ser solicitadas.
  • Percorra cada página dos artigos, crie um arquivo Excel, obtenha o índice de qualidade e escreva-o no 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("获取完成")

Após a execução, você receberá um arquivo Excel contendo todos os dados do artigo e índices de qualidade.

Todos os códigos:

  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("获取完成")

Efeito