爬取今日頭條街拍數(shù)據(jù),練習(xí)ajax數(shù)據(jù)爬取

今日頭條街拍數(shù)據(jù):

代碼:

import requests
import json
import os
from urllib.request import urljoin
from urllib.parse import urlencode
from hashlib import md5



# 獲取單頁數(shù)據(jù)
def getOnePage(offset):
    data = {
        'offset': offset,
        'format': 'json',
        'keyword': '街拍',
        'autoload': 'true',
        'count': '20',
        'cur_tab': '1',
        'from': 'search_tab',
    }
    try:
        url = 'https://www.toutiao.com/search_content/?' + urlencode(data)
        response = requests.get(url)
        if response.status_code == requests.codes.ok:
            return response.json()
    except Exception as f:
        print(f)
        return None
    
# 解析單頁數(shù)據(jù)
def parseOnePage(content):
    if content.get('data'):
        for item in content.get('data'):
            title = item.get('title')
            if title is not None:
                imgList = item.get('image_list')
                for imgUrl in imgList:
                    yield {
                        'title': title,
                        'imgUrl': 'http:'+imgUrl.get('url')
                    }

# 下載圖片
def downloadImg(item):
    if not os.path.exists(item.get('title')):
        os.mkdir(item.get('title'))
    try:
        response = requests.get(item.get('imgUrl'))
        print(response.status_code)
        if response.status_code == requests.codes.ok:
            fileName = md5(response.content).hexdigest() + '.jpg'
            filePath = os.path.join(item.get('title'),fileName)
            if not os.path.exists(filePath):
                with open(filePath, 'wb') as f:
                    f.write(response.content)
            else:
                print('file already Download', filePath)
    except Exception as e:
        print('file download failed!', item.get('imgUrl'))
            
def main(offset):
    content = getOnePage(offset)
    for item in parseOnePage(content):
        downloadImg(item)

if __name__ == '__main__':
    # 使用進(jìn)程池
    from multiprocessing.pool import Pool
    pool = Pool()
    
    GROUP_START = 1
    GROUP_END = 20
    
    groups = ([i*20 for i in range(GROUP_START, GROUP_END+1)])
    pool.map(main, groups)
    pool.close()
    pool.join()
    
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容