python百度圖片爬取

  • 輸入關(guān)鍵字,對百度圖片進(jìn)行爬取。代碼如下:
"""
Created on Sun Jun 17 15:34:19 2018
爬取百度圖片,下載在桌面。
@author: Chen
"""

import requests
import re
from urllib import parse
import os 
import time
import tkinter as tk
import winreg


#利用系統(tǒng)的注冊表來獲取用戶的桌面地址
def GetDesktop():
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,\
    r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',)
    return str(winreg.QueryValueEx(key, "Desktop")[0])


#獲取HTML信息
def GetHtml(url):
    try:
        kv =  
        r = requests.get(url, timeout=5, headers = kv)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        print('爬取失敗')
        
        
#用正則表達(dá)式提取objURL:"(.*?)" ——圖片的地址
def TextParse(text):
    raw = re.compile(r'"objURL":"(.*?)"')
    l = raw.findall(text)    #返回一個list
    return l


#下載圖片,傳入url, 第num張圖, 文件夾名字(以檢索目標(biāo)為名字)
def download(url, num, dirname):
    global fileList     #用于記錄下載文件的大小,以過濾重復(fù)圖片
    path = dirname + '\\a' + str(num) +'.jpg'
    if not os.path.exists(path):
        try:
            r = requests.get(url,timeout = 5, headers ={'user-agent': 'Mozilla/5.0'} )   
            length = len(r.content)
            r.raise_for_status()
            #通過判斷二進(jìn)制文件的大小來過濾掉404的圖片網(wǎng)站和重復(fù)的圖片
            if length > 2000 and length not in fileList:
                fileList.append(len(r.content))
                #下載圖片
                with open(path,'wb') as f:
                    f.write(r.content)
                    f.close()
        except:
            pass  
        
def rename(path):
    File = os.listdir(path)
    for i in range(len(File)):
        os.rename(File[i],"{}.jpg".format(i+1))
    print('\nSuccessfully download :',i)


def GUI():
    t = tk.Tk()
    t.title('百度圖片抓取器')     #標(biāo)題
    t.geometry("100x300")        #窗口大小
    t.resizable(width=False,height=False)   #是否能改變窗口大小,默認(rèn)為True
    
    
if __name__ == '__main__':
    start = time.clock()    #記下程序開始時(shí)間,用于后面計(jì)算總的時(shí)間
    fileList = []
    URLlist = []
    pages =  5      #要爬取的頁面數(shù)
    #initUrl表示百度圖片搜索的地址, targetName表示要檢索的關(guān)鍵字
    initUrl = r'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word='
    targetName = input('輸入你要抓取的關(guān)鍵詞:')
    word = parse.quote(targetName)    #編碼
    DownloadPath = GetDesktop()    #獲取桌面的地址
    os.chdir(DownloadPath)  
    #在下載位置下創(chuàng)建一個以檢索字為名的文件夾用來存放圖片
    try:
        os.mkdir(targetName)
    except:
        raise Exception("桌面已有{}的文件夾!".format(targetName))
        
    os.chdir(targetName)
    print("{:=^40}".format("初始化中")) 
    for i in range(pages): 
        pn = 20*i               #pn為百度圖片頁面的參數(shù),0->第一頁,20->第二頁 ……
        url = initUrl + word + str(pn)
        text = GetHtml(url)
    #抓取頁面上所有圖片的地址存放在URLlist中(經(jīng)過測試,一頁60張,得到60個url連接)
        URLlist = URLlist + TextParse(text)
        lenURL = len(URLlist)
        
    #遍歷URLlist,下載鏈接指向的圖片。
    for i in range(lenURL):
        download(URLlist[i],i,os.getcwd())
        #打印進(jìn)度條
        per = int((i+1)/lenURL*100)
        print("\r{}%[{}{}]{:4.2f}s".format(per, (per//3)*">",\
              (33-per//3)*" ",time.clock()-start),end="")  
    rename(os.getcwd())    #重命名
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容