Python通過URL爬取圖片

上一篇解決的問題是如何通過url獲取圖片,現在來研究如何通過給定的網址獲取網頁中刷出來的圖片。

代碼來自微信公衆號CVPy,這是我在使用Adaboost訓練人臉分類器的時候在CSDN裏面偶然發現的。可以看出是一個很有趣很強的兄弟,向他學習。在調試代碼的過程中,我也自己發現了一些問題:


錯誤:ValueError: Couldn't find a tree builder with the features you requested: xml. Do you need to install a parser library?
辦法:安裝easy_install lxml

錯誤:BeautifulSoup無法正常調用
辦法:只pip install BeautifulSoap不行,要完整地安裝BS4

錯誤:AttributeError: 'str' object has no attribute 'startwith'
辦法:判斷字符串是否以某字符創開始是startswith,不是startwith


完整代碼如下:

# -*- coding=utf-8 -*-
import requests as req
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO
import os
from skimage import io
import numpy as np
import urllib
import cv2
url = 'https://www.zhihu.com/question/37787176'
headers = {'User-Agent' : 'Mozilla/5.0 (Linux;Android 6.0;Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/58.0.3029.96 Mobile Safari/537.36'}
response = req.get(url, headers=headers)
content = str(response.content)
print content
soup = BeautifulSoup(content, "lxml")
images = soup.find_all('img')
print u"共有%d張圖片" % len(images)

if not os.path.exists("images"):
    os.mkdir("images")
for i in range(len(images)):
    img = images[i]
    print u"正在處理第%d張圖片..." % (i+1)
    img_src = img.get('src')
    if img_src.startswith("http"):
        resp = urllib.urlopen(img_src)
        image = np.asarray(bytearray(resp.read()), dtype="uint8")
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)
        w,h = image.shape[:2]
        print w,h
        img_path = "images/" + str(i+1) + ".jpg"
        if w>=200 and h>200:
            cv2.imshow("Image", image)
            cv2.waitKey(3000)
print u"處理完成"

結果就是下面這個樣子,存儲圖片的方式多種,在上篇“Python通過url獲取圖片的幾種方法”中有介紹。



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