logo
Loading...

Grab 得到的Response,無法儲存成圖片 - Cupoy

【問題】利用Grab實作取得PTT圖片的作業,GrabGrab取回的response.body是by...

pycrawler,pycrawler-d10

Grab 得到的Response,無法儲存成圖片

2019/12/11 上午 00:14
Python網路爬蟲討論版
賴彥錡
觀看數:6
回答數:1
收藏數:1
pycrawler
pycrawler-d10

【問題】

利用Grab實作取得PTT圖片的作業,GrabGrab取回的response.body是byte型別,轉成 BytesIO 要儲存成圖片時會發生錯誤。


【程式碼】

import os,io

from grab import Grab

from pyquery import PyQuery as pq

g = Grab()

resp = g.go('https://www.ptt.cc/bbs/Beauty/M.1556291059.A.75A.html', cookies={'over18':'1'})

doc = pq(resp.body)


# 決定要儲存的資料夾

output_dir = 'downloads2'


# 假如資料夾不存在就新增一個資料夾

if not os.path.exists(output_dir):

   os.makedirs(output_dir)


for element in doc('#main-content').children('a'):

   filename = os.path.basename(element.attrib['href'])

   print(filename)

   img_url = 'https://i.imgur.com/{}.jpg'.format(filename)

   print(img_url)

   img_resp = g.go(img_url, encoding='utf-8')


   dataBytesIO = io.BytesIO(img_resp.body)

   with Image.open(dataBytesIO) as img:

       full_path = '{dir}/{name}.{ext}'.format(dir=output_dir, name=filename, ext=img.format.lower())

       # 儲存圖片

img.save(full_path)

       print('儲存圖片 {}'.format(full_path))



【錯誤訊息】

回答列表

  • 2019/12/12 上午 11:47
    張維元 (WeiYuan)
    贊同數:0
    不贊同數:0
    留言數:1

    嗨,這邊可以直接寫入:


    ```

    import io

    from grab import Grab

    from PIL import Image


    g = Grab()

    resp = g.go('https://i.imgur.com/r73M0Z7.jpg')

    open('./image.png', 'wb').write(resp.body)

    ```