2013-03-06 12 views
48

alıyorsanız nasıl anlatmak Yanlış bir URL girildiğinde ve bir 404 hatası döndüğünde. Ben kasıtlı Geçersiz bir URL, girerseniz böyle yaptığımda: İstekler ben İstekler kitaplığı kullanarak ve aşağıdaki kodla ondan veri toplamak için bir web sitesi giriyorum bir 404

print r 

Ben bu olsun:

<Response [404]> 

EDIT:

Bunun için nasıl test bilmek istiyorum. Nesne tipi hala aynı. r.content veya r.text yaptığımda, özel bir 404 sayfasının HTML'sini aldım. r.status_code attribute de

+0

Dokümanlara bakın: http://docs.python-requests.org/en/latest/ İlk sayfa, r.status_code dosyasına bakacak –

cevap

110

Görünüş:

if r.status_code == 404: 
    # A 404 was issued. 

Demo: Eğer hata kodları için bir istisna (4xx veya 5xx) yükseltmek requests istiyorsanız

>>> import requests 
>>> r = requests.get('http://httpbin.org/status/404') 
>>> r.status_code 
404 

, çağrı r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404') 
>>> r.raise_for_status() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "requests/models.py", line 664, in raise_for_status 
    raise http_error 
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND 
>>> r = requests.get('http://httpbin.org/status/200') 
>>> r.raise_for_status() 
>>> # no exception raised. 

Ayrıca yanıt nesnesini bir boole conta da test edebilirsiniz Metin; Durum kodu bir hata kodu (4xx veya 5xx) değilse, ‘gerçek’ olarak kabul edilir:

if r: 
    # successful response 

daha açık olmasını istiyorsanız

, if r.ok: kullanın.

İlgili konular