2014-02-18 3 views
0

원격 파일 목록을 다운로드 중입니다. 내 코드는 다음과 같습니다파일을 찾지 못하면 파이썬 요청 다운로드 HTML

try: 
    r = requests.get(url, stream=True, verify=False) 
    total_length = int(r.headers['Content-Length']) 

    if total_length: 
     with open(file_name, 'wb') as f: 
      for chunk in r.iter_content(chunk_size=1024): 
       if chunk: 
        f.write(chunk) 
        f.flush() 

except (requests.RequestException, StandardError): 
    pass 

내 문제는 요청이 일반 존재하지 않는 파일을 HTML (예를 들어, 404 페이지, 또는 자연 HTML 페이지에서 다른 유사한)를 다운로드한다는 것입니다. 이것을 피할 수있는 방법이 있습니까? 확인할 헤더는 Content-Type 일 것입니다. 솔루션

:

내가 허용 대답에 따라, r.raise_for_status() 함수 호출을 사용하고 또한 같은 Content-Type에 대한 추가 검사를 추가 :

if r.headers['Content-Type'].split('/')[0] == "text": 
    #pass/raise here 

(여기 MIME 형식 목록 : http://www.freeformatter.com/mime-types-list.html)

답변

4

r.raise_for_status()을 사용하여 4xx 및 5xx 상태 코드의 응답에 대한 예외를 발생 시키거나 r.status_code ex를 테스트합니다. 명백히.

try: 
    r = requests.get(url, stream=True, verify=False) 
    r.raise_for_status() # raises if not a 2xx or 3xx response 
    total_length = int(r.headers['Content-Length']) 

    if total_length: 
     # etc.  
except (requests.RequestException, StandardError): 
    pass 

r.status_code 체크하면 적절한 응답 코드를 고려 당신이 좁혀 할 것 :

r.raise_for_status() 이미 잡을 RequestException의 서브 클래스 인 HTTPError 예외를 발생시킵니다. 3xx 리다이렉션은 자동으로 처리되며이 경우에는 requests이 조건부 요청을 보내지 않으므로 다른 3xx 응답을 볼 수 없으므로 여기서 명시적인 테스트가 필요하지 않습니다.

r = requests.get(url, stream=True, verify=False) 
r.raise_for_status() # raises if not a 2xx or 3xx response 
total_length = int(r.headers['Content-Length']) 

if 200 <= r.status_code < 300 and total_length: 
    # etc. 
+0

감사합니다 : 당신이 경우에, 그것은처럼 보일 것입니다! 또한 내용 유형에 대한 추가 검사 (text/*가 아닌 경우)를 추가했습니다. – Ion

1
if r.status_code == 404: 
    handle404() 
else: 
    download() 
관련 문제