Grab 得到的Response,無法儲存成圖片
【問題】
利用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)
```