爬取今日頭條Ajax請求
網(wǎng)址:https://www.toutiao.com/
搜索頭條
可以得到這個網(wǎng)址:
https://www.toutiao.com/search/?keyword=%E8%A1%97%E6%8B%8D
開發(fā)者工具查看:
我們在搜索中并沒有發(fā)現(xiàn)上面的文字,那么我們可以初步判定,這個由Ajax加載,然后渲染出來的。此時切換到xhr過濾,可以看到確實是ajax請求。
觀察請求的特點,發(fā)現(xiàn)只有offset是改變的,而且一次加20,。
我們可以用它來控制數(shù)據(jù)分頁,然后把圖片下載下來。代碼如下:
import requests import os from urllib.parse import urlencode from hashlib import md5 from multiprocessing.pool import Pool from requests import codes def get_page(offset): params = { "offset":offset, "format":"json", "keyword":"街拍", "autoload":"true", "count":"20", "cur_tab":"1", "from":"search_tab" } url = 'https://www.toutiao.com/search_content/?'+urlencode(params) try: response = requests.get(url) if response.status_code == 200: # print(url) return response.json() except requests.ConnectionError: return None # get_page(0) def get_images(json): if json.get('data'): for item in json.get('data'): if item.get('cell_type') is not None: continue title = item.get('title') images = item.get('image_list') for image in images: yield { 'title':title, 'image':'https:' + image.get('url'), } def save_image(item): #os.path.sep 路徑分隔符‘//' 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')) # print(type(resp)) if codes.ok == resp.status_code: file_path = img_path + os.path.sep + '{file_name}.{file_suffix}'.format( file_name=md5(resp.content).hexdigest(),#md5是一種加密算法獲取圖片的二進制數(shù)據(jù),以二進制形式寫入文件 file_suffix='jpg') if not os.path.exists(file_path): with open(file_path,'wb')as f: f.write(resp.content) print('Downladed 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(offset) for item in get_images(json): print(item) save_image(item) GROUP = 0 GROUP_END = 2 if __name__ == '__main__': pool = Pool() groups = ([x*20 for x in range(GROUP,GROUP_END)]) pool.map(main,groups) #將groups一個個調(diào)出來傳給main函數(shù) pool.close() pool.join() #保證子進程結束后再向下執(zhí)行 pool.join(1) 等待一秒
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
通達OA 使用Ajax和工作流插件實現(xiàn)根據(jù)人力資源系統(tǒng)數(shù)據(jù)增加OA賬號(圖文詳解)
這篇文章主要介紹了通達OA 使用Ajax和工作流插件實現(xiàn)根據(jù)人力資源系統(tǒng)數(shù)據(jù)增加OA賬號(圖文詳解),需要的朋友可以參考下2016-12-12jquery ajax實現(xiàn)批量刪除具體思路及代碼
回調(diào)函數(shù),在請求完成后需要進行的操作:此處是把選中的checkbox去掉,接下來為大家詳細介紹下,感興趣的朋友可以參考下哈,希望對你有所幫助2013-04-04jQuery ajax json 數(shù)據(jù)的遍歷代碼
最近做了一個項目,其中有需求要進行ajax請求后,后臺傳遞回來以下json數(shù)據(jù)。下面小編給大家分享我的實現(xiàn)思路,需要的朋友參考下2016-06-06