[Python][爬蟲03]requests+BeautifulSoup實例:抓取圖片並保存

    上一篇中,安裝和初步使用了requests+BeautifulSoup,感受到了它們的便捷。但之前我們抓取的都是文字信息,這次我們準備來抓取的是圖片信息。

>第一個實例

    我們來抓取這個網站的圖片:http://www.ivsky.com/bizhi/stand_by_me_doraemon_v45983/

    首先,審查網頁元素:


    因此其結構就爲:

<div class='il_img'> x 若干個,對每個div有 :
    <img src='我們要的img src數據'>

    整體思路是:

  • 獲取每個圖片的src地址;
  • 構建requests去請求img的src並獲取圖片;
  • 寫入文件

    代碼如下:

import requests
from bs4 import BeautifulSoup
pic_id = 0  # 圖片編號
url = 'http://www.ivsky.com/bizhi/stand_by_me_doraemon_v45983/'
bs = BeautifulSoup(requests.get(url).content, "lxml")  # 調用lxml作爲解析引擎 需要:pip install lxml
for i in bs.select('.il_img'):
    pic_url = i.find('img')['src']
    pic_file = open('./pic_'+str(pic_id)+'.jpg', 'wb')  # 二進制創建並寫入文件
    pic_file.write(requests.get(pic_url).content)  # 寫出請求得到的img資源
    pic_id += 1

    這樣,就能在爬蟲腳本目錄下找到我們需要的圖片了:



>第二個實例

    這次我們來抓取這個網站的資源,要的是獎章圖標+獎章等級+等級標誌顏色+稱號,並按照'等級+標誌顏色+稱號.gif'的方式存儲:


    結構爲:

<table>
    <td>
        <img> img-src
    <td> 等級
    <td> 顏色
    <td> 稱號

    同樣,也就可以給出相關的代碼了:

import re
import requests
from bs4 import BeautifulSoup
url = 'http://ol.kuai8.com/gonglue/236751_all.html'
bs = BeautifulSoup(requests.get(url).content, "lxml")
for table in bs.find_all('table', attrs={'border': 1, 'align': 'center'}):  # 獲取所有的數據表
    for td in table.find_all(td_with_img): # 獲取含有img標籤的td標籤
        img_src = td.img['src'] # 獲取圖片url
        level = td.find_next_sibling('td')  # 等級td節點
        color = level.find_next_sibling('td') # 顏色td節點
        title = color.find_next_sibling('td')  # 稱號td節點
        opf = open(get_title(level.string, color.string, title.string), 'wb')
        opf.write(requests.get(img_src).content)
        print '已抓取:', re.sub('\s', '', level.string)

    這裏用了兩個方法:

def td_with_img(node):
    return node.name == 'td' and node.img is not None  # 含有img標籤的td標籤 
def get_title(level, color, title):
    return './ppt/'+re.sub('\s', '', level)+re.sub('\s', '', color)+re.sub('\s', '', title)+'.gif' # 移除空白並直接得到文件名

    我們的成果:


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