Python實現百度圖片的爬取

# -*- encoding: utf-8 -*-
import requests
import os
import urllib

def Search(name,localpath,page):
    #os.makedirs(localpath)  #這裏創建文件夾路徑,exist_ok=True 指如果有就不創建
    params = {
        'tn':'resultjson_com',
        'catename':'pcindexhot',
        'ipn':'rj',
        'ct':'201326592',
        'is':'',
        'fp':'result',
        'queryWord':'',
        'cl':'2',
        'lm':'-1',
        'ie':'utf-8',
        'oe':'utf-8',
        'adpicid':'',
        'st':'-1',
        'z':'',
        'ic':'0',
        'word':name,
        'face':'0',
        'istype':'2',
        'qc':'',
        'nc':'1',
        'fr':'',
        'pn':'0',
        'rn':'30'
        };
    params['pn'] = '%d' % page
    Request(params,localpath)
    return ;

def Request(param,path):
    searchurl  = 'http://image.baidu.com/search/avatarjson'     #百度圖片
    response = requests.get(searchurl,params =param )           #傳入請求參數
    json  = response.json()['imgs']                             #每張圖片有自己的下載路徑
    for i in range(0,len(json)):
        filename = os.path.split(json[i]['objURL'])[1]
        Download(json[i]['objURL'],filename,path)

def Download(url,filename,filepath):
    path = os.path.join(filepath,filename)                      #這裏我們還是採用原來的圖片
    try:                                                        #有些圖片不知道爲什麼下載不了,所以這裏用了try的方式
        urllib.urlretrieve(url,path)
        print('Downloading Images From ', url)
    except:
        print('Downloading None Images!')

#下載的主函數
if __name__ =='__main__':
    name=raw_input("輸入要下載的關鍵詞:")
    page_start=raw_input("輸入開始下載頁碼:")
    page_end=int(raw_input("輸入要連續下載頁碼數量:"))+int(page_start)
    for i in range(int(page_start),page_end):
        Search(name,'images/',i)

該代碼,根據別人代碼改寫,加入自定義頁碼和自定義關鍵字。

原文章地址:沒找到(那個作者也許會很傷心),記得是個怕老虎相關的圖片的爬蟲。

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