기술나눔

모든 CSDN 게시 기사의 해당 데이터를 얻기 위한 Python 함수 생성

2024-07-12

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

안녕하세요 여러분, 오늘은 실용적인 내용을 공유하고 싶습니다.파이썬 스크립트 를 사용하면 CSDN 블로그에 게시된 모든 기사의 관련 데이터를 일괄적으로 가져오고 해당 데이터를 Excel 파일에 저장하는 데 도움이 될 수 있습니다. 또한 스크립트는 각 기사의 품질 점수를 얻고 이 점수를 Excel에도 기록합니다. 시작하자!

스크립트 기능 개요

이 스크립트는 주로 두 부분으로 나뉩니다.

  1. 기사 정보를 얻고 Excel에 저장: 이 부분에서는 CSDN API에서 기사 목록을 가져오고 주요 정보를 Excel 파일에 저장합니다.
  2. 기사 품질 점수 확인 및 Excel 업데이트: 각 기사에 대한 품질 점수를 요청하고 이 점수를 해당 Excel 파일에 추가하는 부분입니다.

구현 단계

1. 필요한 라이브러리 가져오기

먼저 이 작업을 수행하는 데 도움이 되는 일부 Python 라이브러리를 가져와야 합니다.

  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. 기사 정보를 얻고 저장하도록 정의합니다.뛰어나다유형

우리는 클래스를 정의합니다GetInformationToExcel기사 정보 가져오기 및 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)

이 클래스에서는 다음 메서드를 구현합니다.

  • __init__: 클래스의 기본 속성을 설정하는 초기화 방법입니다.
  • get_articles: 기사 목록을 얻으려면 CSDN API에 HTTP GET 요청을 보냅니다.
  • export_to_excel: 기사 목록을 Pandas DataFrame으로 변환하여 엑셀 파일로 저장합니다.

3. 기사 품질 점수를 얻기 위한 범주 정의

다음으로 다른 클래스를 정의합니다.GetArticleScores기사 품질 점수 획득 및 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)

이 클래스에서는 다음 메서드를 구현합니다.

  • __init__: 클래스의 기본 속성을 설정하는 초기화 방법입니다.
  • get_article_score: 정적 메서드는 기사의 품질 점수를 얻기 위해 API에 HTTP POST 요청을 보냅니다.
  • get_scores_from_excel: 엑셀 파일을 읽고, 기사 URL 목록을 가져오고, 점수 목록을 가져옵니다.
  • write_scores_to_excel: Excel 파일을 DataFrame으로 읽어 들여 얻은 점수를 DataFrame에 추가하고 다시 Excel 파일에 저장합니다.

4. 주요 프로그램

마지막으로 메인 프로그램에서 총 기사 수, 쿠키, 리퍼러 및 CSDN 사용자 ID를 설정하고 다음 단계를 수행했습니다.

  • 요청해야 하는 페이지 수를 계산합니다.
  • 기사의 각 페이지를 반복하면서 Excel 파일을 만들고 품질 점수를 받아 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("获取完成")

실행 후에는 모든 기사 데이터와 품질 점수가 포함된 Excel 파일을 받게 됩니다.

모든 코드:

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

효과