data_handler.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """
  2. """
  3. import json
  4. import logging
  5. import re
  6. import jsonpath
  7. from util import json_util
  8. user_require_fields = ['id', 'name', 'profile_picture', 'profile_url']
  9. def get_post_by_doc(response):
  10. data = get_post_json(response.text())[0]['node']
  11. content_story = jsonpath.jsonpath(data, 'comet_sections.content.story')[0]
  12. logging.info('获取成功')
  13. # item = {k: v for k, v in item.items() if k in blog_require_fields}
  14. # item['cover'] = item['image_versions2']['candidates'][0]['url']
  15. # item['image_versions2'] = None
  16. # item['user'] = {k: v for k, v in item['user'].items() if k in user_require_fields}
  17. # comet_sections.context_layout.story.comet_sections.actor_photo.story.actors
  18. actor = jsonpath.jsonpath(data, '$..comet_sections.context_layout.story.comet_sections.actor_photo.story.actors[0]')[0]
  19. actor = {k: v for k, v in actor.items() if k in user_require_fields}
  20. result = {
  21. 'text': content_story['message']['text'],
  22. 'attachments': jsonpath.jsonpath(data, '$..styles.attachment.all_subattachments.nodes'),
  23. 'post_id': content_story['post_id'],
  24. 'actor': actor,
  25. 'creation_time': jsonpath.jsonpath(data, '$..comet_sections.context_layout.story.comet_sections.metadata[0].story.creation_time')[0],
  26. 'id': content_story['id'],
  27. 'reaction_count': jsonpath.jsonpath(data, '$..comet_ufi_summary_and_actions_renderer.feedback.reaction_count.count')[0],
  28. 'comment_count': jsonpath.jsonpath(data, '$..comment_rendering_instance_for_feed_location.comments.total_count')[0],
  29. 'share_count': jsonpath.jsonpath(data, '$..comet_ufi_summary_and_actions_renderer.feedback.share_count.count')[0]
  30. }
  31. # 图片
  32. return result
  33. def get_blog_json(html_content):
  34. # 逐行读取文件
  35. inside_items = False # 标志是否进入 items 部分
  36. items_buffer = "" # 临时保存 JSON 部分
  37. for line in html_content.splitlines():
  38. # 通过简单的规则修复非标准 JSON 格式(可以根据实际情况定制)
  39. line = line.strip() # 去掉多余的空白字符
  40. if '"xdt_api__v1__media__shortcode__web_info"' in line:
  41. items_buffer = '{'
  42. inside_items = True # 发现目标字段
  43. continue
  44. # 处理 items 数组的部分
  45. if inside_items:
  46. items_buffer += line # 累积读取多行
  47. # 如果找到了 JSON 数组的结束
  48. if '"items": [' in items_buffer and ']' in items_buffer:
  49. try:
  50. # 尝试解析 JSON
  51. data = json.loads(items_buffer)
  52. # 获取第一个 item
  53. return data
  54. except json.JSONDecodeError:
  55. continue # 如果解析失败,继续读取下一行
  56. return None # 如果没有找到匹配项
  57. def get_post_json(html_content):
  58. # 逐行读取文件
  59. for line in html_content.splitlines():
  60. # 通过简单的规则修复非标准 JSON 格式(可以根据实际情况定制)
  61. line = line.strip() # 去掉多余的空白字符
  62. # pattern = r'adp_Comet\w+ContentQueryRelayPreloader_\w+",(\{.+?\})'
  63. pattern = r'adp_Comet\w+ContentQueryRelayPreloader_\w+",\{(.*)'
  64. # pattern = r'adp_Comet\w+ContentQueryRelayPreloader_\w+",(.*)'
  65. match = re.search(pattern, line, re.DOTALL)
  66. if match:
  67. # print(line)
  68. json_part = match.group(1)
  69. pattern = r'\"data\"\:\{(.*)}'
  70. json_part = re.search(pattern, json_part, re.DOTALL)
  71. data = json_util.parse_json_from_string('{' + json_part.group(1))
  72. # print(story)
  73. # jsonpath_expr = '$..xdt_api__v1__media__shortcode__web_info.items[0]' # 寻找第一个 item
  74. # data = jsonpath.jsonpath(data, jsonpath_expr)
  75. # if data:
  76. # return data[0]
  77. return data
  78. return None # 如果没有找到匹配项
  79. def get_user_by_request(response):
  80. response_json = response.json()
  81. if response_json.get('status') == 'ok' and 'data' in response_json:
  82. user = response_json['data']['user']
  83. user = {k: v for k, v in user.items() if k in user_require_fields}
  84. return user
  85. else:
  86. return None