प्रौद्योगिकी साझेदारी

सर्वेषां CSDN प्रकाशितलेखानां तत्सम्बद्धदत्तांशं प्राप्तुं पायथन् फंक्शन् उत्पादनम्

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. लेखसूचना प्राप्तुं परिभाषयन्तु तथा च तस्मिन् रक्षन्तुExcelप्रकारः

वयं वर्गं परिभाषयामः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__: वर्गस्य मूलभूतगुणान् सेट् कर्तुं Initialization method ।
  • get_articles: लेखसूचीं प्राप्तुं CSDN API - मध्ये HTTP GET अनुरोधं प्रेषयन्तु ।
  • export_to_excel: लेखसूचीं Pandas DataFrame इत्यत्र परिवर्त्य Excel सञ्चिकायां रक्षन्तु ।

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__: वर्गस्य मूलभूतगुणान् सेट् कर्तुं Initialization method ।
  • get_article_score: स्थिरविधिः, लेखस्य गुणवत्तास्कोरं प्राप्तुं HTTP POST अनुरोधं एपिआइ प्रति प्रेषयति ।
  • get_scores_from_excel: Excel सञ्चिकां पठन्तु, लेखस्य URL सूचीं प्राप्नुवन्तु, स्कोरसूचीं च प्राप्नुवन्तु।
  • write_scores_to_excel: Excel सञ्चिकां DataFrame मध्ये पठन्तु, प्राप्तानि स्कोरं DataFrame मध्ये योजयित्वा पुनः Excel सञ्चिकायां रक्षन्तु ।

4. मुख्य कार्यक्रम

अन्ते वयं मुख्यकार्यक्रमे लेखानाम्, कुकीजानां, Referer, CSDN user 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("获取完成")

परिणाम