美文网首页
Ajax分析,多线程爬虫爬取新浪微博图片

Ajax分析,多线程爬虫爬取新浪微博图片

作者: Mstarece | 来源:发表于2019-05-02 15:29 被阅读0次

一,分析网页请求

我们打开新浪微博首页,以杨超越的微博为例,打开开发者工具,我们得到杨超越微博首页url: https://m.weibo.cn/u/5644764907?uid=5644764907

查看第一个请求,请求返回的网页源代码,并没有此时微博网页上面文字和图片信息,也和Elements里面的不相同,因此猜测,新浪微博是先搭好前端框架通过ajax请求,最后将数据填入相应的位置。

因此查看XHR里面的请求,发现有一个请求,返回了主页里面的一些信息

我们继续下拉网页,发现 请求:https://m.weibo.cn/api/container/getIndex?    带有如下3个重要参数

因此我们发现请求时要携带这3个参数, page为当前访问返回的页数

我们得到最终要访问杨超越微博请求的url :  https://m.weibo.cn/api/container/getIndex?uid=5644764907&containerid=1076035644764907&page=1


二,发送请求并解析数据

1.首先写请求,其中Use-Agent 为自己浏览器的信息,通过开发者工具可以查看。 经测试也可以不用编写请求头,也能够返回正确的数据。

2.编写请求,返回json数据,通过urlencode()方法,将params变成Get 请求的风格。

3.解析json数据,我们要爬取的是微博内容的图片,其他的信息也同理。 图片地址在data ,cards,mblog,pics下面。

其中large下的 url 里面的图片地址为原图,正是我们想要获取的数据,因此解析json数据的代码如下。

有的微博 itemid 和 图片为空,如果后面再用get方法会报错  'NoneType' object has no attribute 'get',因此当遇到这种情况跳过就好了。


三,保存到本地,采用多线程方法

将一张图片的保存到本地的代码如下,dir 为文件目录,filename为文件名字。

在批量下载时,我们采用多线程的方法,默认开启10线程同时下载图片

最后看一下主函数

程序运行起来时

四,总结

    通过分析请求和响应的结果,分析出微博采用的是ajax的方式,向服务器请求数据的。然后找到请求的api,分析其携带的参数,写爬虫的程序,最后采用多线程下载图片到本地。

转载请注明原文章地址


五,感谢

当你看到这里的时候,我还是比较欣慰的,谢谢你们的支持! 我现在还是一个努力学习的大学生,写的有问题希望指出来! 我之后还会和大家分享一些我学习的笔记,机器学习,python,java等和你们一起共同进步!!加油

联系方式: biexingxing@icloud.com

微博:  Mstarece

最后直接贴上源代码!!!

from multiprocessing.dummyimport Pool

from urllib.parseimport urlencode

import requests

import time

import os

base_url ='https://m.weibo.cn/api/container/getIndex?'

headers = {

'Host':'m.weibo.cn',

'Referer':'https://m.weibo.cn/u/',

'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',

'X-Requested-With':'XMLHttpRequest'

}

def get_page(page):

params = {

'uid':'5644764907',

'containerid':'1076035644764907',

'page': page

}

url = base_url + urlencode(params)

try:

response = requests.get(url,headers=headers)

if response.status_code ==200:

return response.json()

except requests.ConnectionErroras e:

print('Request Error', e.args)

def parse_page(json):

if json:

pics = []

items = json.get('data').get('cards')

content = items[0].get('mblog').get('user').get('screen_name') +'的微博图片'

        for itemin items:

itemid = item.get('itemid')

if itemid =='':

continue

            item_pics = item.get('mblog').get('pics')

if item_pics ==None:

continue

            else:

for item_picin item_pics:

url = item_pic.get('large').get('url')

pics.append(url)

return pics,content

def save_to_file(pic,content):

url = pic

dir ='Imgs' +'/' + content

filename = dir +'/' + url.split('/')[-1]

if os.path.exists(filename):

print('exists:', filename)

return

    if not os.path.exists(dir):

try:

os.makedirs(dir)

except Exception as e:

pass

    res = requests.get(url)

with open(filename,'wb')as fp:

print('start download', url)

fp.write(res.content)

def Async(pics,content,processes=10):

start_time = time.time()

pool = Pool(processes)

for imgin pics:

pool.apply_async(save_to_file, (img,content))

pool.close()

pool.join()

end_time = time.time()

print('下载完毕,用时:%s秒' % (end_time - start_time))

def mian():

for pagein range(1,10):

json = get_page(page)

pics, content = parse_page(json)

Async(pics, content)

if __name__ =='__main__':

mian()

相关文章

网友评论

      本文标题:Ajax分析,多线程爬虫爬取新浪微博图片

      本文链接:https://www.haomeiwen.com/subject/auimnqtx.html