python爬蟲,一段完整的python爬蟲批量下載網站圖片資源的代碼


# 本程序為爬蟲學習代碼,成功爬取了漫微網站上的全部圖片內容
import re
import os
import requests

def getHTMLText(url):
    try:
        r=requests.get(url)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        print("request failed")

url = 'http://marvel.mtime.com/' # 漫微網址
web_data = getHTMLText(url)  # web_data保存目標url的html代碼內容
res = re.compile(r'src="(.+?.jpg)"') # 定義查詢規則,所有以src開頭,中間包含任意多個字符的,並且結尾為.jpg的文件被
                                    #提取並保存
reg = re.findall(res, web_data) # 在web_data中找到並提取滿足res規則的全部字符串,並保存在reg列表
for i in reg:
    target_url = url + i      # 變量target_url獲得圖片的url
    try:
        pic = requests.get(target_url).content # 從target_url下載了圖片,並以二進制的形式保存在變量pic中
    except:
        print(target_url + 'can not open')
    res = re.compile(r'images/(.+?.jpg)')
    pic_name = re.findall(res, i)[0]  #提取圖片文件名,從結果數組第[0]個元素獲得具體文件名
    print(pic_name)
    with open(pic_name, 'wb') as f:
        f.write(pic)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM