ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

通过分析ajax网页获取今日头条街拍美图

2019-03-01 13:53:11  阅读:230  来源: 互联网

标签:file get image item ajax 美图 import path 头条


首先解释下什么是ajax动态网页,刷微博会经常遇见这种,往下一直拉取,就会一直有数据在加载,然后显示在你的界面,类似于下图。
在这里插入图片描述
也能发现,该网页是通过改变offset(步长为20),来加载数据(观察改步是通过的XHR标签)
然后抓取数据。
有待学习google开发者F12
network
如果看ajax加载,需要XHR标签
如果看源码,需要Doc标签
待有机会,详细解析代码,目前只是崔老师的成功爬取的代码,有pool层

from requests.exceptions import RequestException
import json
import re
from bs4 import BeautifulSoup
import requests
from urllib.parse import urlencode
from requests import codes   # ?from 和 import 的区别
import os
from hashlib import md5   # ?
from multiprocessing.pool import Pool   # 多进程池

def get_page_index(offset, keyword):
    data = {
        'offsets': offset,
        'format': 'json',
        'keyword': keyword,
        'autoload': 'true',
        'count': '20',
        'cur_tab': 3
    }
    url = 'http://www.toutiao.com/search_content/?' + urlencode(data)  # 这是网页的地址,urlencode是url的一种编码方式
    try:
        response = requests.get(url)
        if response.status_code == codes.ok:
            return response.json()
    except requests.ConnectionError:
        print('请求索引出错')
        return None

def get_images(json):
    if json.get('data'):
        data = json.get('data')
        for item in data:
            if item.get('cell_type') is not None:
                continue
            title = item.get('title')
            images = item.get('image_list')
            for image in images:
                yield {
                    'image': 'https:' + image.get('url'),
                    'title': title
                }

def save_image(item):
    img_path = 'img' + os.path.sep + item.get('title')
    if not os.path.exists(img_path):
        os.makedirs(img_path)
    try:
        resp = requests.get(item.get('image'))
        if codes.ok == resp.status_code:
            file_path = img_path + os.path.sep + '{file_name}.{file_suffix}'.format(
                file_name=md5(resp.content).hexdigest(),
                file_suffix='jpg')
            if not os.path.exists(file_path):
                with open(file_path, 'wb') as f:
                    f.write(resp.content)
                print('Downloaded image path is %s' % file_path)
            else:
                print('Already Downloaded', file_path)
    except requests.ConnectionError:
        print('Failed to Save Image,item %s' % item)

def main(offset):
    json = get_page_index(offset,'街拍')
    for item in get_images(json):
        print(item)
        save_image(item)

GROUP_START = 0
GROUP_END = 7

if __name__ == '__main__':
    pool = Pool()
    groups = ([x * 20 for x in range(GROUP_START,GROUP_END + 1)])
    pool.map(main,groups) # 池化匹配
    pool.close()
    pool.join()

标签:file,get,image,item,ajax,美图,import,path,头条
来源: https://blog.csdn.net/ACBattle/article/details/84679828

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有