python+requests抓取頁面圖片

前言:     

學完requests庫後,想到能夠利用python+requests爬取頁面圖片,想到實戰一下。依照如今所學只能爬取圖片在html頁面的而不能爬取由JavaScript生成的圖片,因此我選取餓了打開下面這個頁面http://p.weather.com.cn/2017/06/2720826.shtml#p=7html

案例步驟:

1.利用requests庫,調用requests庫中的get()方法,打開須要爬去的頁面url,返回頁面內容,下面是自定義的打開頁面的方法python

def load_page(url):
    response=requests.get(url)
    data=response.content
    return data

2.用正則表達式去匹配頁面的圖片連接,匹配成功後,把圖片下載下來,保存到對應的文件位置,下面是自定義的保存圖片方法正則表達式

def get_image(html):
    regx=r'http://[\S]*jpg'
    pattern=re.compile(regx)
    get_images=re.findall(pattern,repr(html))

    num=1
    for img in  get_images:
        image=load_page(img)
        with open('./spider_picture/%s.jpg' % num,'wb') as fb:
            fb.write(image)
            print("正在下載第%s張圖片" %num)
            num=num+1
    print("下載完成!")

  完整案例源碼:

# coding:utf-8
# 引入requests包和正則表達式包re
import requests
import re

# 自定義下載頁面函數
def load_page(url):
    response=requests.get(url)
    data=response.content
    return data

# 自定義保存頁面圖片函數
def get_image(html):
    regx=r'http://[\S]*jpg'  # 定義圖片正則表達式
    pattern=re.compile(regx) # 編譯表達式構造匹配模式
    get_images=re.findall(pattern,repr(html)) # 在頁面中匹配圖片連接

    num=1
    # 遍歷匹配成功的連接
    for img in  get_images:
        image=load_page(img) #根據圖片連接,下載圖片連接
        # 將下載的圖片保存到對應的文件夾中
        with open('./spider_picture/%s.jpg' % num,'wb') as fb:
            fb.write(image)
            print("正在下載第%s張圖片" %num)
            num=num+1
    print("下載完成!")

# 定義爬取頁面的連接
url ='http://p.weather.com.cn/2017/06/2720826.shtml#p=7'
# 調用load_page函數,下載頁面內容
html = load_page(url)
# 在頁面中,匹配圖片連接,並將圖片下載下來,保存到對應文件夾
get_image(html)            
相關文章
相關標籤/搜索