python爬取微博某一用户所有个人信息及视频图片

  1. import os  
  2. import shutil  
  3. import requests  
  4. import json  
  5. from lxml import html  
  6. import time  
  7. import re  
  8. import urllib.request  
  9.   
  10.   
  11. headers = {  
  12.     # 'Cookies':'SUB=_2A25xgwvUDeRhGeBN7FoU9SzJyzmIHXVSj5WcrDV6PUJbkdAKLWrukW1NRArvY5Bm433yk8F2VI-rnvIJU6E9sZpJ; SUHB=010GCPyqzcv2w4; SCF=AmxfXClfex8bJruLjpDGuj_HkiQ0ruLZt7O5LBUqsqttQtoskRiPxXPI-zaCehtuzjU-YbhbLWBIwQIvvcmN1VE.; SSOLoginState=1552382852; _T_WM=6ca499957ef4fe628d21dbf0971e2a27; MLOGIN=1; WEIBOCN_FROM=1110006030; XSRF-TOKEN=863cd5; M_WEIBOCN_PARAMS=luicode%3D10000011%26lfid%3D100103type%253D1%2526q%253D%25E6%25A0%25A1%25E8%258D%2589%26fid%3D10080818b3ed999cd7b9b893ddf2ee3414346f%26uicode%3D10000011',  
  13.     'Cookies':'SUB=_2A25xgwvUDeRhGeBN7FoU9SzJyzmIHXVSj5WcrDV6PUJbkdAKLWrukW1NRArvY5Bm433yk8F2VI-rnvIJU6E9sZpJ; SUHB=010GCPyqzcv2w4; SCF=AmxfXClfex8bJruLjpDGuj_HkiQ0ruLZt7O5LBUqsqttQtoskRiPxXPI-zaCehtuzjU-YbhbLWBIwQIvvcmN1VE.; SSOLoginState=1552382852; _T_WM=6ca499957ef4fe628d21dbf0971e2a27; MLOGIN=1; WEIBOCN_FROM=1110006030; XSRF-TOKEN=09566d; M_WEIBOCN_PARAMS=luicode%3D10000011%26lfid%3D10080818b3ed999cd7b9b893ddf2ee3414346f_-_feed%26fid%3D1005052914737397%26uicode%3D10000011',  
  14.     'Host': 'm.weibo.cn',  
  15.     # 'Referer':'https://m.weibo.cn/p/index?containerid=10080818b3ed999cd7b9b893ddf2ee3414346f&luicode=10000011&lfid=100103type%3D1%26q%3D%E6%A0%A1%E8%8D%89',  
  16.     'Referer':'https://m.weibo.cn/sw.js',  
  17.     'Upgrade-Insecure-Requests': '1',  
  18.     'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',  
  19. }  
  20.   
  21. # user_url ='https://m.weibo.cn/api/container/getIndex?containerid=10080818b3ed999cd7b9b893ddf2ee3414346f_-_main&luicode=10000011&lfid=100103type%3D1%26q%3D%E6%A0%A1%E8%8D%89'  
  22.   
  23. user_url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=2914737397&containerid=1076032914737397'  
  24.   
  25.   
  26. tmp_folder_name = 'WeiboData_'  
  27. tmp_folder_time = '2019_'  
  28. user_name = '颜值圈'  
  29.   
  30.   
  31. txt_file_name = '_Weibo_DataRecords.txt'  
  32.   
  33. num_page = 2  
  34.   
  35. path = tmp_folder_name + tmp_folder_time + user_name + '/'  
  36. if os.path.exists(path) is True:  
  37.     shutil.rmtree(path)  
  38. os.mkdir(path)  
  39.   
  40. print('\n' + 40 * '=' + '\n' + 'Crawling Weibo data of user - ' + user_name + '.\n' + 40 * '=')  
  41.   
  42.   
  43. print('\n' + 40 * '=' + '\n' + 'The number of crawling pages is: ' + str(num_page) + '.' + '\n' + 40 * '=' + '\n')  
  44.   
  45. ii = 0  
  46. list_cards = []  
  47.   
  48. while ii < num_page:  
  49.     ii += 1  
  50.     print('Start crawling "cards" on page %d/%d.' % (ii, num_page))  
  51.       
  52.     url = user_url + '&page=' + str(ii)  
  53.     response = requests.get(url, headers=headers)  
  54.     ob_json = json.loads(response.text)  
  55.     list_cards.append(ob_json['data']['cards'])  
  56.     time.sleep(5)  
  57.     print('Complete!')  
  58.   
  59. # print('list_cards:',list_cards)  
  60.   
  61. print('\n' + 40 * '=' + '\n' + 'The number of crawling pages is: ' + str(len(list_cards)) + '.' + '\n' + 40 * '=' + '\n')  
  62.   
  63. count_weibo = 0  
  64. page_weibo = 0  
  65.   
  66. for cards in list_cards:  
  67.     page_weibo += 1  
  68.       
  69.     for card in cards:  
  70.         count_weibo += 1  
  71.         print('Start crawling the ' + str(count_weibo) + '-th post on ' + str(page_weibo) + '-th page.')  
  72.           
  73.         if card['card_type'] == 9:  
  74.             mid = card['mblog']['id']  
  75.             created_at = card['mblog']['created_at']  # The posted time.  
  76.               
  77.             # 1/3 Crawl text.  
  78.             if card['mblog']['isLongText'] == 'False':  # Note: 'False' != 'false'.  
  79.                 text = card['mblog']['text']  
  80.             else:  
  81.                 try:  
  82.                     tmp_url = 'https://m.weibo.cn/statuses/extend?id=' + mid  
  83.                     tmp_response = requests.get(tmp_url, headers=headers)  
  84.                     ob_json = json.loads(tmp_response.text)  # ob_json (dict)  
  85.                     text = ob_json['data']['longTextContent']  
  86.                     tree = html.fromstring(text)  
  87.                     text = tree.xpath('string(.)')  
  88.                 except:  
  89.                     text = "No short text extracted!"  
  90.   
  91.             # Save text.  
  92.             with open(path + user_name + txt_file_name, 'a', encoding='utf-8') as ff:  
  93.                 ff.write('\n' + 'The ' + str(count_weibo) + '-th weibo\n' + '***  Published on  ' + created_at + '  ***' + '\n')  
  94.                 ff.write(text + '\n')  
  95.               
  96.             # 2/3 Crawl JPG/GIF images.  
  97.             if 'bmiddle_pic' in card['mblog']:  
  98.                 tag_post = 1  # 1 - original post.  
  99.             else:  
  100.                 tag_post = 2  # 2 - re-tweeted post.  
  101.               
  102.             if (tag_post == 1) or (tag_post == 2):  # Save all post.  
  103.                 # Create a child folder for saving images.  
  104.                 image_path = path + str(count_weibo)  
  105.                 os.mkdir(image_path)  
  106.                   
  107.                 url_extend = 'https://m.weibo.cn/status/' + mid  # URL of one Weibo.  
  108.                 res = requests.get(url_extend, headers=headers).text  # <'string'>  
  109.                   
  110.                 imgjpg_url_weibo = re.findall('https://.*large.*.jpg', res)  # Match URL of JPG images <'string'>.  
  111.                 imggif_url_weibo = re.findall('https://.*large.*.gif', res)  # Match URL of GIF images <'string'>.  
  112.                   
  113.                 # 2-1/3 Crawl JPG images.  
  114.                 x_jpg = 0  # The serial number of JPG image.  
  115.                   
  116.                 for i in range(len(imgjpg_url_weibo)):  
  117.                     x_jpg += 1  
  118.                       
  119.                     # Add JPG image URL to .txt file.  
  120.                     temp = image_path + '/' + str(x_jpg) + '.jpg'  
  121.                     with open(path + user_name + txt_file_name, 'a', encoding='utf-8') as ff:  
  122.                         ff.write('The link of the image is:' + imgjpg_url_weibo[i] + '\n')  
  123.                     print('Download the %s-th image.' % x_jpg)  
  124.                       
  125.                     # Download JPG image.  
  126.                     try:  
  127.                         urllib.request.urlretrieve(urllib.request.urlopen(imgjpg_url_weibo[i]).geturl(), temp)  
  128.                     except:  
  129.                         print("Failed to download the image: %s" % imgjpg_url_weibo[i])  
  130.                   
  131.                 # 2-2/3 Crawl GIF images.  
  132.                 x_gif = 0  # The serial number of GIF image.  
  133.                   
  134.                 for i in range(len(imggif_url_weibo)):  
  135.                     x_gif += 1  
  136.                       
  137.                     # Add GIF image URL to .txt file.  
  138.                     temp = image_path + '/' + str(x_gif) + '.gif'  
  139.                     with open(path + user_name + txt_file_name, 'a', encoding='utf-8') as ff:  
  140.                         ff.write('The link of the image is:' + imggif_url_weibo[i] + '\n')  
  141.                     print('Download the %s-th image.' % x_gif)  
  142.                       
  143.                     # Download GIF image.  
  144.                     try:  
  145.                         urllib.request.urlretrieve(urllib.request.urlopen(imggif_url_weibo[i]).geturl(), temp)  
  146.                     except:  
  147.                         print("Failed to download the image: %s" % imggif_url_weibo[i])  
  148.               
  149.             # 3/3 Crawl videos.  
  150.             if 'page_info' in card['mblog']:  
  151.                 if 'media_info' in card['mblog']['page_info']:  # Filter Weibo posts with video that has 'page_info' index.  
  152.                     # Create a child folder for saving video.  
  153.                     video_path = path + str(count_weibo) + '_video'  
  154.                     os.mkdir(video_path)  
  155.                       
  156.                     videourl_weibo = card['mblog']['page_info']['media_info']['mp4_sd_url']  # <'string'>  
  157.                     # Note:  
  158.                     #     This code obtains the URL of video.  
  159.                     #     The index is manually parsed from DevTools.  
  160.                       
  161.                     temp = video_path + '/' + str(1) + '.mp4'  
  162.                     print('Download the video.')  # Each Weibo post only has one video.  
  163.                       
  164.                     # Download video.  
  165.                     try:  
  166.                         urllib.request.urlretrieve(urllib.request.urlopen(videourl_weibo).geturl(), temp)  
  167.                     except:  
  168.                         print("Failed to download the video.")  
  169.           
  170.         time.sleep(6)  # Suspend * seconds after crawling data from one Weibo post.  
  171.         print('Complete!\n')  
  172.       
  173.     print('Complete crawling Weibo data on ' + str(page_weibo) + '-th page!' + '\n\n' + 40 * '-' + '\n')  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值