just-coding-it
파이썬으로 네이버 웹툰을 압축해보자
fffman
2022. 11. 22. 00:27
지난번엔 네이버 웹툰을 다운로드 하는 과정을 경험해봤다.
파이썬으로 네이버 웹툰을 다운로드 받아보자
오늘은 네이버 웹툰을 다운로드 해볼 예정이다. 네이버 웹툰은 처음 응답받는 HTML에 모든 이미지 src가 들어있기 때문에 굉장히 쉽게 다운로드 받을 수 있다. 시험대에 오를 작품은 호랑이형님 1
f-three.tistory.com
이번엔 파일 하나하나를 파일로 만들지 않고, 바로 압축파일로 저장해보도록 하겠다.
파이썬에서는 압축하는 기능을 ZipFile이라는 클래스를 통해서 제공한다. 간단하게 사용법을 보면 아래와 같다.
from zipfile import ZipFile
with ZipFile('test.zip', 'w') as zf:
file_name = 'test.txt'
zf.write(file_name)
test.txt라는 경로에 있는 파일을 test.zip이라는 압축파일로 만들었다. 그런데 이런 방식은 우리가 원한 방식이 아니다. 다운로드 받은 이미지 파일을 저장장치에 저장하지 않고 바로 압축파일을 만드는것이 목표다. 그렇기 때문에 BytesIO라는 클래스를 활용할 수 있다. 아래 예시를 참고하여 이해해볼 수 있다.
from zipfile import ZipFile
from io import BytesIO
# 파일을 메모리로 불러옴
file_name = 'test.txt'
with open(file_name, 'rb') as f:
file_bytes = f.read()
# 메모리상의 데이터를 압축함
bytes_io = BytesIO()
with ZipFile(bytes_io, 'w') as zf:
zf.writestr(file_name, file_bytes)
# 압축한 데이터를 저장장치에 저장함
with open('test.zip', 'wb') as f:
f.write(bytes_io.getvalue())
그러면 기존 다운로드 코드를 어떻게 수정하면 될 지 알 수 있다. 아래 코드와 같이 수정하면 된다.
import requests
from bs4 import BeautifulSoup as bs
from zipfile import ZipFile
from io import BytesIO
def get_html(url):
response = requests.get(url)
return response.text
def get_img_urls(html):
soup = bs(html, 'html.parser')
imgs = soup.select('#comic_view_area > .wt_viewer > img')
for img in imgs:
yield img['src']
def get_img_bytes(url):
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
return response.content
if __name__ == '__main__':
url = 'https://comic.naver.com/webtoon/detail?titleId=650305&no=1&weekday=sat'
html = get_html(url)
img_urls = get_img_urls(html)
bytes_io = BytesIO()
with ZipFile(bytes_io, 'w') as zf:
for i, img_url in enumerate(img_urls, start=1):
img_name = f'./{i}.jpg'
img_bytes = get_img_bytes(img_url)
zf.writestr(img_name, img_bytes)
print(f'--complete-- {i}')
with open('webtoon_1.zip', 'wb') as f:
f.write(bytes_io.getvalue())