[宅男福利]用Python下載頁面中所有的圖片


思路分析


首先利用Python的Requests庫去獲取參數(shù)中頁面的內(nèi)容 , 然后進行使用BeautifulSoup庫進行解析 , 解析到圖片以后開啟多線程進行下載保存


截圖展示 :


Paste_Image.png
Paste_Image.png

代碼實現(xiàn) :


#!/usr/bin/env python
#encoding:utf8

import requests
import threading
from bs4 import BeautifulSoup
import sys
import os

# config-start
url = sys.argv[1]
threadNumber = 20 # 設(shè)置線程數(shù)
# config-end

def getContent(url):
    response = requests.get(url)
    response.encoding = 'utf-8' # 設(shè)置相應(yīng)體的字符集
    return response.text

def getTitle(soup):
    return soup.title.string.encode("GBK")

def getImageLinks(soup):
    imgs = soup.findAll("img")
    result = []
    for img in imgs:
        result.append(img)
    return result

def makeDirectory(dicName):
    if not os.path.exists(dicName):
        os.mkdir(dicName)

def downloadImage(imgUrl,savePath): 
    local_filename = imgUrl.split('/')[-1] 
    local_filename = formatFileName(local_filename)
    r = requests.get(imgUrl, stream=True) 
    counter = 0
    if not savePath.endswith("\\"):
        savePath += "\\"
    f = open(savePath + local_filename, 'wb')
    for chunk in r.iter_content(chunk_size=1024): 
        if chunk: 
            f.write(chunk) 
            f.flush()
            counter += 1
    f.close()

def formatFileName(fileName):
    fileName = fileName.replace("/","_")
    fileName = fileName.replace("\\","_")
    fileName = fileName.replace(":","_")
    fileName = fileName.replace("*","_")
    fileName = fileName.replace("?","_")
    fileName = fileName.replace("\"","_")
    fileName = fileName.replace(">","_")
    fileName = fileName.replace("<","_")
    fileName = fileName.replace("|","_")
    fileName = fileName.replace(" ","_")
    return fileName

def threadFunction(imgSrc,directoryName):
    downloadImage(imgSrc,directoryName)

class myThread (threading.Thread):
    def __init__(self, imgSrc, directoryName):
        threading.Thread.__init__(self)
        self.imgSrc = imgSrc
        self.directoryName = directoryName

    def run(self):
        threadFunction(self.imgSrc, self.directoryName)


content = getContent(url)
soup = BeautifulSoup(content, "html.parser")
images = getImageLinks(soup)
title = getTitle(soup)
title = formatFileName(title)
print u"頁面標(biāo)題 : " , title
print u"本頁圖片數(shù)量 :",len(images)
print u"正在創(chuàng)建文件夾以用來保存所有圖片"
makeDirectory(title)
threads = []

for image in images:
    src = image['src']
    print u"圖片地址 : " + src
    threads.append(myThread(str(src), str(title)))

for t in threads:
    t.start()
    while True:
        if(len(threading.enumerate()) < threadNumber):
            break

print u"所有圖片下載完成 ! "

后記 :

之前的腳本在處理某些網(wǎng)站的時候容錯性還不是很強 , 這里將腳本簡單修改了一下
新版本代碼如下
#!/usr/bin/env python
#encoding:utf8

import requests
import threading
from bs4 import BeautifulSoup
import sys
import os

if len(sys.argv) != 2:
    print("Usage : ")
    print("        python main.py [URL]")
    exit(1)

# config-start
url = sys.argv[1]
threadNumber = 20 # 設(shè)置線程數(shù)
# config-end

def getContent(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        response.encoding = response.apparent_encoding
        return response.text
    except Exception as e:
        print(e)
        return str(e)

def getTitle(soup):
    try:
        return soup.title.string
    except:
        return "UnTitled"

def getImageLinks(soup):
    imgs = soup.findAll("img")
    result = []
    for img in imgs:
        try:
            src = img['src']
            if src.startswith("http"):
                result.append(img['src'])
            else:
                result.append(domain + img['src'])
        except:
            continue
    return result

def makeDirectory(dicName):
    if not os.path.exists(dicName):
        os.mkdir(dicName)

def downloadImage(imgUrl,savePath):
    local_filename = imgUrl.split('/')[-1]
    local_filename = formatFileName(local_filename)
    r = requests.get(imgUrl, stream=True)
    counter = 0
    if not savePath.endswith("/"):
        savePath += "/"
    f = open(savePath + local_filename + ".png", 'wb')
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:
            f.write(chunk)
            f.flush()
            counter += 1
    f.close()

def formatFileName(fileName):
    fileName = fileName.replace("/","_")
    fileName = fileName.replace("\\","_")
    fileName = fileName.replace(":","_")
    fileName = fileName.replace("*","_")
    fileName = fileName.replace("?","_")
    fileName = fileName.replace("\"","_")
    fileName = fileName.replace(">","_")
    fileName = fileName.replace("<","_")
    fileName = fileName.replace("|","_")
    fileName = fileName.replace(" ","_")
    return fileName

def threadFunction(imgSrc,directoryName):
    downloadImage(imgSrc,directoryName)

class myThread (threading.Thread):
    def __init__(self, imgSrc, directoryName):
        threading.Thread.__init__(self)
        self.imgSrc = imgSrc
        self.directoryName = directoryName

    def run(self):
        threadFunction(self.imgSrc, self.directoryName)


def getPrefix(url):
    # http://doamin/xxx.jpg
    return ''.join(i+"/" for i in url.split("/")[0:4])

def getDomain(url):
    return ''.join(i+"/" for i in url.split("/")[0:3])



content = getContent(url)
prefix = getPrefix(url)
domain = getDomain(url)
soup = BeautifulSoup(content, "html.parser")
images = getImageLinks(soup)
title = getTitle(soup)
title = formatFileName(title)
print(u"頁面標(biāo)題 : " , title)
print(u"本頁圖片數(shù)量 :",len(images))
print(u"正在創(chuàng)建文件夾以用來保存所有圖片")
makeDirectory(title)
threads = []

for image in images:
    print(u"圖片地址 : " + image)
    threads.append(myThread(image, title))

for t in threads:
    t.start()
    while True:
        if(len(threading.enumerate()) < threadNumber):
            break

print(u"所有圖片已加入下載隊列 ! 正在下載...")

測試結(jié)果 :

image.png
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,822評論 6 427
  • GitHub 上有一個 Awesome - XXX 系列的資源整理,資源非常豐富,涉及面非常廣。awesome-p...
    若與閱讀 19,300評論 4 417
  • 環(huán)境管理管理Python版本和環(huán)境的工具。p–非常簡單的交互式python版本管理工具。pyenv–簡單的Pyth...
    MrHamster閱讀 3,949評論 1 61
  • 快餐式的時尚,每一秒都在改變著,不知道下一刻又要流行哪一種「你看不懂的時尚」。 大家都知道韓系風(fēng)廣受大家喜愛,更多...
    細七閱讀 384評論 0 0
  • 公公喜歡研究家族歷史,這些年把老家楊氏家譜編寫好出書,現(xiàn)在又尋思著要建宗祠。這次來廣州的心愿就是去看下廣州的以前遺...
    米菲的游樂園閱讀 590評論 1 0

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