data_handler.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """
  2. """
  3. import json
  4. import re
  5. import jsonpath
  6. from util import json_util
  7. blog_require_fields = ['code', 'pk', 'id', 'taken_at', 'image_versions2', 'user', 'media_type', 'carousel_media',
  8. 'carousel_media_count',
  9. 'like_count', 'comment_count', 'caption', 'caption_is_edited']
  10. user_require_fields = ['pk', 'id', 'username', 'full_name', 'profile_pic_url', 'latest_reel_media', 'follower_count',
  11. 'following_count', 'media_count']
  12. def get_blog_by_doc(response):
  13. item = get_blog_json2(response.text())
  14. item = {k: v for k, v in item.items() if k in blog_require_fields}
  15. item['cover'] = item['image_versions2']['candidates'][0]['url']
  16. item['image_versions2'] = None
  17. item['user'] = {k: v for k, v in item['user'].items() if k in user_require_fields}
  18. return item
  19. def get_blog_json(html_content):
  20. # 逐行读取文件
  21. inside_items = False # 标志是否进入 items 部分
  22. items_buffer = "" # 临时保存 JSON 部分
  23. for line in html_content.splitlines():
  24. # 通过简单的规则修复非标准 JSON 格式(可以根据实际情况定制)
  25. line = line.strip() # 去掉多余的空白字符
  26. if '"xdt_api__v1__media__shortcode__web_info"' in line:
  27. items_buffer = '{'
  28. inside_items = True # 发现目标字段
  29. continue
  30. # 处理 items 数组的部分
  31. if inside_items:
  32. items_buffer += line # 累积读取多行
  33. # 如果找到了 JSON 数组的结束
  34. if '"items": [' in items_buffer and ']' in items_buffer:
  35. try:
  36. # 尝试解析 JSON
  37. data = json.loads(items_buffer)
  38. # 获取第一个 item
  39. return data
  40. except json.JSONDecodeError:
  41. continue # 如果解析失败,继续读取下一行
  42. return None # 如果没有找到匹配项
  43. def get_blog_json2(html_content):
  44. # 逐行读取文件
  45. for line in html_content.splitlines():
  46. # 通过简单的规则修复非标准 JSON 格式(可以根据实际情况定制)
  47. line = line.strip() # 去掉多余的空白字符
  48. if '"xdt_api__v1__media__shortcode__web_info"' in line:
  49. script_pattern = re.compile(r'<script\s+type="application/json"[^>]*>(.*?)</script>', re.DOTALL)
  50. # 查找所有匹配的 <script> 标签内容
  51. json_str = re.findall(script_pattern, line)
  52. data = json.loads(json_str[0])
  53. jsonpath_expr = '$..xdt_api__v1__media__shortcode__web_info.items[0]' # 寻找第一个 item
  54. data = jsonpath.jsonpath(data, jsonpath_expr)
  55. if data:
  56. return data[0]
  57. return None # 如果没有找到匹配项
  58. def get_user_by_request(response):
  59. response_json = response.json()
  60. if response_json.get('status') == 'ok' and 'data' in response_json:
  61. user = response_json['data']['user']
  62. user = {k: v for k, v in user.items() if k in user_require_fields}
  63. return user
  64. else:
  65. return None