從豆瓣爬取並下載對應關鍵字的全部圖片(以周杰倫爲例)

源碼

import requests
import json

def download(src, id):
    dir = './' + str(id) + '.jpg'
    try:
        pic = requests.get(src, timeout=10)
    except requests.exceptions.ConnectionError:
        # print 'error, %d 當前圖片無法下載', %id
        print('圖片無法下載')
    fp = open(dir, 'wb')
    fp.write(pic.content)
    fp.close()

def loop_request(total, text):
    for i in range(0, total, 20):
        url = 'https://www.douban.com/j/search_photo?q=' + text + '&limit=20&start=' + str(i)
        html = requests.get(url).text  # 得到返回結果
        response = json.loads(html, encoding='utf-8')  # 將JSON格式轉換成Python對象
        for image in response['images']:
            print('downloading ' + image['src'])
            # 查看當前下載的圖片網址
            download(image['src'], image['id'])  # 下載一張圖片

def get_count(text):
    url = 'https://www.douban.com/j/search_photo?q=' + text + '&limit=20&start=1'
    html = json.loads(requests.get(url).text, encoding='utf-8')
    print(html)
    print(html['total'])
    loop_request(html['total'], text)

get_count('周杰倫')

簡要說明

  • 其中包含三個函數
  • get_count用於獲取該關鍵字對應圖片的數量
  • loop_request根據圖片總數量,20個一組獲取圖片
  • download下載圖片並根據id保存至本地

環境介紹

  • python版本 3.0+
  • 開發工具 PyCharm

END

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章