Python基于分析Ajax請求實現(xiàn)抓取今日頭條街拍圖集功能示例
本文實例講述了Python基于分析Ajax請求實現(xiàn)抓取今日頭條街拍圖集功能。分享給大家供大家參考,具體如下:
代碼:
import os import re import json import time from hashlib import md5 from multiprocessing import Pool import requests from requests.exceptions import RequestException from pymongo import MongoClient # 配置信息 OFFSET_START = 0 # 爬去頁面的起始下標 OFFSET_END = 20 # 爬去頁面的結(jié)束下標 KEYWORD = '街拍' # 搜索的關(guān)鍵字 # mongodb相關(guān)配置 MONGO_URL = 'localhost' MONGO_DB = 'toutiao' # 數(shù)據(jù)庫名稱 MONGO_TABLE = 'jiepai' # 集合名稱 # 圖片保存的文件夾名稱 IMAGE_PATH = 'images' headers = { "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' } client = MongoClient(host=MONGO_URL) db = client[MONGO_DB] jiepai_table = db[MONGO_TABLE] if not os.path.exists(IMAGE_PATH): os.mkdir(IMAGE_PATH) def get_html(url, params=None): try: response = requests.get(url, params=params, headers=headers) if response.status_code == 200: return response.text return None except RequestException as e: print("請求%s失敗: " % url, e) return None # 獲取索引頁內(nèi)容 def get_index_page(offset, keyword): basic_url = 'http://www.toutiao.com/search_content/' params = { 'offset': offset, 'format': 'json', 'keyword': keyword, 'autoload': 'true', 'count': 20, 'cur_tab': 3 } return get_html(basic_url, params) def parse_index_page(html): ''' 解析索引頁內(nèi)容 返回: 索引頁中包含的所有詳情頁url ''' if not html: return data = json.loads(html) if 'data' in data: for item in data['data']: article_url = item['article_url'] if 'toutiao.com/group' in article_url: yield article_url # 獲取詳情頁 def get_detail_page(url): return get_html(url) # 解析詳情頁 def parse_detail_page(url, html): ''' 解析詳情頁 返回對應的標題,url和包含的圖片url ''' title_reg = re.compile('<title>(.*?)</title>') title = title_reg.search(html).group(1) gallery_reg = re.compile('var gallery = (.*?);') gallery = gallery_reg.search(html) if gallery and 'sub_images' in gallery.group(1): images = json.loads(gallery.group(1))['sub_images'] image_list = [image['url'] for image in images] return { 'title': title, 'url': url, 'images': image_list } return None def save_to_mongodb(content): jiepai_table.insert(content) print("存儲到mongdob成功", content) def download_images(image_list): for image_url in image_list: try: response = requests.get(image_url) if response.status_code == 200: save_image(response.content) except RequestException as e: print("下載圖片失敗: ", e) def save_image(content): ''' 對圖片的二進制內(nèi)容做hash,構(gòu)造圖片路徑,以此保證圖片不重復 ''' file_path = '{0}/{1}/{2}.{3}'.format(os.getcwd(), IMAGE_PATH, md5(content).hexdigest(), 'jpg') # 去除重復的圖片 if not os.path.exists(file_path): with open(file_path, 'wb') as f: f.write(content) def jiepai(offset): html = get_index_page(offset, KEYWORD) if html is None: return page_urls = list(parse_index_page(html)) # print("詳情頁url列表:" ) # for page_url in page_urls: # print(page_url) for page in page_urls: print('get detail page:', page) html = get_detail_page(page) if html is None: continue content = parse_detail_page(page, html) if content: save_to_mongodb(content) download_images(content['images']) time.sleep(1) print('-------------------------------------') if __name__ == '__main__': offset_list = range(OFFSET_START, OFFSET_END) pool = Pool() pool.map(jiepai, offset_list)
備注:
其實通過url請求返回的json數(shù)據(jù)中已經(jīng)包含了圖片列表
import requests basic_url = 'http://www.toutiao.com/search_content/?offset={}&format=json&keyword=%E8%A1%97%E6%8B%8D&autoload=true&count=20&cur_tab=3' url = basic_url.format(0) html = requests.get(url).json() items = html['data'] for item in items: title = item['media_name'] image_list = [image_detail['url'] for image_detail in item['image_detail']] print(title, image_list)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python URL操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python通過ssh-powershell監(jiān)控windows的方法
這篇文章主要介紹了python通過ssh-powershell監(jiān)控windows的方法,涉及Python操作ssh-powershell的相關(guān)技巧,需要的朋友可以參考下2015-06-06使用sklearn進行對數(shù)據(jù)標準化、歸一化以及將數(shù)據(jù)還原的方法
今天小編就為大家分享一篇使用sklearn進行對數(shù)據(jù)標準化、歸一化以及將數(shù)據(jù)還原的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07Python數(shù)組拼接np.concatenate實現(xiàn)過程
這篇文章主要介紹了Python數(shù)組拼接np.concatenate實現(xiàn)過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04python中使用ctypes調(diào)用so傳參設(shè)置遇到的問題及解決方法
這篇文章主要介紹了python中使用ctypes調(diào)用so傳參設(shè)置,本文較詳細的給大家介紹了遇到問題及解決方案,需要的朋友可以參考下2019-06-06如何用 Python 子進程關(guān)閉 Excel 自動化中的彈窗
這篇文章主要介紹了如何用 Python 子進程關(guān)閉 Excel 自動化中的彈窗,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下2021-05-05numpy.bincount用于復數(shù)權(quán)重的方法
numpy.bincount是NumPy庫中的一個函數(shù),它用于計算整數(shù)數(shù)組中每個值的出現(xiàn)次數(shù),numpy.bincount函數(shù)在統(tǒng)計整數(shù)數(shù)組中每個值的出現(xiàn)次數(shù)或權(quán)重和時非常有用,本文給大家介紹numpy.bincount如何用于復數(shù)權(quán)重,感興趣的朋友跟隨小編一起看看吧2023-11-11