개발/python

파이썬 requests 이미지 다운로드 에러 처리[403,permission]

북치기_개발모드 2022. 9. 21. 12:19
반응형

작업 특성상 디렉토리 몇 개를 거치는 경로를 설정해야 했다.

첫 번째로 시도한 건 curl인데, 이건 경로 지정하는 방식을 못 찾겠어서 포기했다.

두 번째는 request를 활용한 urlretrieve 방식인데, 인터넷 예시를 참조했다.

import requests

url = "https://dispatch.cdnser.be/cms-content/uploads/2020/04/09/a26f4b7b-9769-49dd-aed3-b7067fbc5a8c.jpg"

urllib.request.urlretrieve(url, "test.jpg")

urllib.error.HTTPError: HTTP Error 403: Forbidden 이런 에러가 발생하였다.

전형적 크롤링 에러로, 헤더를 추가해줘야 하는데, 이 상태로는 해더를 넣을 수가 없었다.

코드를 좀 변형하여 헤더를 추가해주었다.

import requests
import os

dir_now = os.path.dirname(os.path.abspath(__file__))

r = requests.get(url,headers=headers)

with open(dir_now, "wb") as outfile:
     outfile.write(r.content)

 

이렇게 하면 될 줄 알았는데 퍼미션 에러가 떠버렸다.

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\

with open(dir_now, "wb") as outfile:

찾아보니 퍼미션 에러는 대부분 경로지정을 잘못했거나,

파일이름을 넣어야 할 때 경로를 넣거나 하는 부분에서 장애가 발생한다고 한다.

https://118k.tistory.com/424

 

내 경우에는 dir_now 부분에 디렉터리 경로가 아닌, 파일 이름을 넣어보니 해결됐다.

완성본

import requests

dir_now = os.path.dirname(os.path.abspath(__file__))

r = requests.get(url,headers=headers)

with open(f'{dir_now}/test.jpg', "wb") as outfile:
     outfile.write(r.content)

 

저 부분은 변수 처리를 하여 반복문을 돌리면 해결될 일이다.

 

참고하였음.

 

[python][error] PermissionError: [Errno 13] Permission denied: ...

PermissionError: [Errno 13] Permission denied: 파이썬에서 파일을 오픈하려고 할때 위와 같은 오류가 발생할 때가 있다. 이오류는 다음의 경우에 발생한다. - 파일을 오픈할 수 있는 권한이 없을때. - 파일

118k.tistory.com

 

반응형