再次爬取乾貨集中營的福利圖片

值得學習的地方html

1.utc時間轉換成普通時間的函數,也就是把2015-06-05T03:54:29.403Z格式的時間轉換成2015-06-05 11:54:29python

2.使用requrests獲取https連接開頭的圖片數據json

 

以前爬取過乾貨集中營的照片,地址:https://www.cnblogs.com/sanduzxcvbnm/p/9209544.htmlapi

今天再重爬一次,換了一種通俗易懂的方式瀏覽器

首先分析網站函數

1.網站地址:https://gank.io/,要爬取的是網站上展現出來的圖片學習

2.在網站首頁有API地址,點進去查看發現是乾貨集中營 API 文檔,網站

其中有這樣一個數據顯示url

嘗試訪問:https://gank.io/api/data/福利/10/1,出來以下json數據spa

 

 

3.經過API文檔描述,能夠知道連接地址中的請求個數和請求頁數,獲取到全部的圖片信息

好比:https://gank.io/api/data/福利/700/1,請求700條數據,獲取第一頁,發現返回的結果中總共有668條數據(截止到20190115),第二頁沒有數據

再次請求:https://gank.io/api/data/福利/600/1,請求600條數據,獲取第一頁,發現確實有600條數據,而後再請求第二頁(https://gank.io/api/data/福利/600/2),有68條數據

結合以上分析,截止到今天(20190115),共有668條數據,避免使用翻頁的狀況,就直接使用以下網址獲取所有數據:https://gank.io/api/data/福利/700/1

其次根據獲取到的數據,提取出所須要的圖片連接

最後下載這些圖片並保存

#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import os from _md5 import md5 import requests from requests import RequestException def get_one_page(url): try: response = requests.get(url) if response.status_code == 200: return response.json() except: return None def utc_to_local(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%S.%fZ'): """ "2015-06-05T03:54:29.403Z"格式的時間轉換成2015-06-05 11:54:29 """ local_format = "%Y-%m-%d %H:%M:%S" utc_dt = datetime.datetime.strptime(utc_time_str, utc_format) local_dt = utc_dt + datetime.timedelta(hours=8) time_str = local_dt.strftime(local_format) return time_str def https_to_http(url): """ 把圖片連接是https的換成http """ if url[0:5] == 'https': url = url.replace(url[0:5], 'http') return url def parse_one_page(html): items = html['results'] for item in items: yield { 'id': item['_id'], 'publishedAt': utc_to_local(item['publishedAt']), 'url': https_to_http(item['url']) } # 請求圖片url,獲取圖片二進制數據 def download_image(url): try: response = requests.get(url) if response.status_code == 200: save_image(response.content) # response.contenter二進制數據 response.text文本數據 return None except RequestException: print('請求圖片出錯', url) return None def save_image(content): """ 須要提早建好目錄D:\\pachong\\gank\\ """ file_path = 'D:\\pachong\\gank\\{1}.{2}'.format(os.getcwd(), md5(content).hexdigest(), 'jpg') if not os.path.exists(file_path): with open(file_path, 'wb') as f: f.write(content) def main(): url = 'http://gank.io/api/data/福利/700/1' html = get_one_page(url) for item in parse_one_page(html): download_image(item['url']) if __name__ == '__main__': main()

最終結果顯示:

總共668條數據,實際只有558條數據,經過分析獲取到的圖片url,發現有些圖片url連接自己已失效,使用瀏覽器打開這些圖片連接會報以下錯誤:

 

 

失效連接展現:

相關文章
相關標籤/搜索