当前位置:   article > 正文

【python】爬取微博内容_python爬取微博内容

python爬取微博内容

某大大在微博上更文,老翻来翻去的太麻烦,一时兴起便想用python爬一下,结果保存为txt文档

目前列出了 文章的网站版url 保存为JSON文件

  • 先贴一下代码
  • 原代码 https://blog.csdn.net/d1240673769/article/details/74278547(下面略作修改)
  1. # -*- coding: utf-8 -*-
  2. # author-Svv 18.08.16
  3. # 爬取手机版微博个人主页中的文章链接
  4. # 代码来源 https://blog.csdn.net/d1240673769/article/details/74278547
  5. import urllib.request
  6. import json
  7. import re
  8. from bs4 import BeautifulSoup
  9. #定义要爬取的微博大V的微博ID 一串数字
  10. id='更换'
  11. #小说名字
  12. art_name = '小说名字'
  13. #设置代理IP
  14. proxy_addr="122.241.72.191:808"
  15. title_list = []
  16. #定义页面打开函数
  17. def use_proxy(url,proxy_addr):
  18. req=urllib.request.Request(url)
  19. req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36")
  20. proxy=urllib.request.ProxyHandler({'http':proxy_addr})
  21. opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
  22. urllib.request.install_opener(opener)
  23. data=urllib.request.urlopen(req,timeout=10).read().decode('utf-8','ignore')
  24. return data
  25. #获取微博主页的containerid,爬取微博内容时需要此id
  26. def get_containerid(url):
  27. data=use_proxy(url,proxy_addr)
  28. content=json.loads(data).get('data')
  29. for data in content.get('tabsInfo').get('tabs'):
  30. if(data.get('tab_type')=='weibo'):
  31. containerid=data.get('containerid')
  32. return containerid
  33. #获取微博内容信息,并保存到文本中,内容包括:每条微博的内容、微博详情页面地址、点赞数、评论数、转发数等
  34. def get_weibo(id):
  35. i=1
  36. while True:
  37. url='https://m.weibo.cn/api/container/getIndex?type=uid&value='+id
  38. weibo_url='https://m.weibo.cn/api/container/getIndex?type=uid&value='+id+'&containerid='+get_containerid(url)+'&page='+str(i)
  39. try:
  40. data=use_proxy(weibo_url,proxy_addr)
  41. content=json.loads(data).get('data')
  42. cards=content.get('cards') #duilie
  43. # print(cards)
  44. if (i<=13):
  45. for j in range(len(cards)):
  46. print("-----正在爬取第" + str(i) + "页,第" + str(j) + "条微博------")
  47. card_type = cards[j].get('card_type')
  48. if (card_type == 9):
  49. mblog = cards[j].get('mblog')
  50. page_info = mblog.get('page_info')
  51. # print(page_info)
  52. if (page_info != None):
  53. content = page_info.get('content1')
  54. # print(content)
  55. if(re.findall(art_name,content) == [art_name]):
  56. # print('**'+content+'**')
  57. created_at = mblog.get('created_at')
  58. text = mblog.get('text')
  59. soup = BeautifulSoup(text,"lxml")
  60. for link in soup.find_all('a'):
  61. if(link.get('data-url') != None):
  62. art_url = link.get('data-url')
  63. title_list.append({
  64. 'content': content,
  65. 'time': str(created_at),
  66. 'art-url': art_url
  67. })
  68. i += 1
  69. else:
  70. break
  71. except Exception as e:
  72. print(e)
  73. pass
  74. # print(title_list)
  75. def main():
  76. get_weibo(id)
  77. line_d = json.dumps(title_list, ensure_ascii=False) # json.dumps()函数是将字典转化为字符串
  78. line_j = json.loads(line_d) # json.loads()函数是将字符串转化为字典
  79. with open('title_url.json', 'w') as fp:
  80. json.dump(line_j, fp)
  81. if __name__=="__main__":
  82. main()
  • 说明:
    • 代理IP直接拿的源代码中的 没有删改 我用的时候还能用
    • id和art_name 需要赋值
    • print(card)可以找到自己需要的变量
    • 还有一篇参考文章 https://www.cnblogs.com/cmai/p/7967847.html

下面贴一下cards的结构,明白这个结构就可以找到自己想要的内容了

  1. {
  2. 'card_type': 9,
  3. 'itemid': '**********',
  4. 'scheme': '**********',
  5. 'mblog': {'created_at': '07-22', 'id': '**********', 'idstr': '4264686415012792', 'mid': '4264686415012792',
  6. 'can_edit': False,
  7. 'text': '<a href="**********" data-hide=""><span class="surl-text">**********
  8. </span></a>**********<a data-url="**********"
  9. href="**********"
  10. data-hide="">',
  11. 'textLength': 234,
  12. 'source': '微博 weibo.com',
  13. 'favorited': False,
  14. 'is_paid': False, 'mblog_vip_type': 0,
  15. 'user': {'id': **********, 'screen_name': '**********',
  16. 'profile_image_url': '**********g',
  17. 'profile_url': '**********',
  18. 'statuses_count': 3071, 'verified': False, 'verified_type': -1, 'close_blue_v': False,
  19. 'description': '**********', 'gender': 'f',
  20. 'mbtype': 11, 'urank': 34, 'mbrank': 4, 'follow_me': False, 'following': False, 'followers_count': 15337,
  21. 'follow_count': 114, 'cover_image_phone': '**********',
  22. 'avatar_hd': '**********', 'like': False, 'like_me': False,
  23. 'badge': {'bind_taobao': 1, 'zongyiji': 1, 'follow_whitelist_video': 1, 'user_name_certificate': 1}
  24. },
  25. 'reposts_count': 20, 'comments_count': 65, 'attitudes_count': 144, 'pending_approval_count': 0, 'isLongText': False, 'hide_flag': 0,
  26. 'visible': {'type': 0, 'list_id': 0},
  27. 'mblogtype': 0, 'more_info_type': 0, 'content_auth': 0,
  28. 'edit_config': {'edited': False},
  29. 'weibo_position': 1,
  30. 'page_info': {
  31. 'page_pic': {'url': '**********'},
  32. 'page_url': '**********',
  33. 'page_title': **********',
  34. 'content1': '**********',
  35. 'content2': '',
  36. 'icon': '**********',
  37. 'type': 'article', 'object_id': '1022:2309404264686416735534'
  38. },
  39. 'bid': 'Gr8MVl23u'
  40. },
  41. 'show_type': 0
  42. }
  • 说明
    • 有些内容用****注释了

下一篇准备把文章内容全爬出来 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57164
推荐阅读
相关标签
  

闽ICP备14008679号