python编程篇之爬虫(四)

本文介绍了一种使用Python和Ajax技术爬取今日头条街拍图片的方法。通过构造URL参数并发送请求,解析返回的JSON数据,获取图片链接及标题,然后下载并保存图片到本地文件夹。此教程详细展示了如何自动化地从网站抓取特定类型的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python+ajax实现今日头条街拍图片爬取

from urllib.parse import urlencode,quote
import urllib.request
import requests
import os
from hashlib import md5


def get_page(num):
    keyword = '街拍'
    base_url = 'https://www.toutiao.com/search_content/?'
    # key = quote(keyword)
    params = {
        'offset':num,
        'format':'json',
        'keyword':keyword,
        'autoload':'true',
        'count':'20',
        'cur_tab':'1',
        'from':'search_tab'
    }
    url = base_url+urlencode(params)

    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.json()
    except requests.ConnectionError:
        return None


def get_image(json):
    if json.get('data'):
        for item in json.get('data'):
            title = item.get('title')
            images = item.get('image_list')
            for image in images:
                yield {
                    'image':image.get('url'),
                    'title':title
                    }


def save_image(item):
    if not os.path.exists(item.get('title')):
        os.mkdir(item.get('title'))
        try:
            response = requests.get(item.get('image'))
            if response.status_code == 200:
                filepath = '{0}/{1}.jpg'.format(item.get('title'),md5(response.content).hexdigest())
                if not os.path.exists(filepath):
                    with open(filepath, 'wb') as fh:
                        fh.write(response.content)
                else:
                    print('Already Download!')
        except requests.ConnectionError:
            print('Fail to save image!')

if __name__ == '__main__':
    for i in range(1,21):
        json = get_page(i*20)
        for item in get_image(json):
            print(item)
            save_image(item)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值