2013-04-08 1 views
3

일부 URL을 살펴보고 사용중인 API에서 대부분의 데이터를 가져올 수 있습니다. * Imgur API. 그 전에 게시되어 결국 제거 된 이미지를 발견하지만 때 여전히 긍정적 인 URL은 응답 (코드 200)를 얻을 보여주고, 내가ValueError : JSON 객체가 디코딩 될 수는 없지만 양수 일 수 있습니다. <Response [200]>

j1 = json.loads(r_positive.text) 

를 사용할 때이 오류가 얻을 :

http://imgur.com/gallery/cJPSzbu.json 
<Response [200]> 
Traceback (most recent call last): 
    File "image_poller_multiple.py", line 61, in <module> 
    j1 = json.loads(r_positive.text) 
    File "/usr/lib/python2.7/json/__init__.py", line 326, in loads 
    return _default_decoder.decode(s) 
    File "/usr/lib/python2.7/json/decoder.py", line 366, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode 
    raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 

대신 j1 변수에서 오류를 "가져올"수 있습니까? 조건 구조를 사용하여 문제를 해결하고 내 프로그램이 충돌하지 않도록하고 싶습니다.

if j1 == ValueError: 
    continue 
else: 
    do_next_procedures() 
+0

귀하의 예를 들어 URL이 http://imgur.com/cJPSzbu에 나를 리디렉션, 나에게 발견 (302)을 제공합니다. 200 OK라고 확신합니까? – Fabian

답변

6

같은 뭔가 대신 tryexcept를 사용해야합니다 :

try: 
    j1 = json.loads(r_positive.text) 
except ValueError: 
    # decoding failed 
    continue 
else: 
    do_next_procedures() 

파이썬 튜토리얼에서 Handling Exceptions를 참조하십시오.

무엇이 실제로일까요? 해당 URL로 리디렉션되어 대신 이미지 페이지가 표시됩니다.

if r_positive.history: 
    # more than one request, we were redirected: 
    continue 
else: 
    j1 = r_positive.json() 

을하거나 심지어 리디렉션을 허용 할 수 : 당신이 JSON을 가져 requests를 사용하는 경우, 대신 the response history 볼 나열된

r = requests.post(url, allow_redirects=False) 
if r.status == 200: 
    j1 = r.json() 
+0

항상 그렇듯이, @martijn, 뛰어난 조언, 제어 구조의 기본적인 파이썬 흐름 중 하나. BTW 100K에 축하해! –

+0

좋은 답변입니다! 감사! – Arturo

+2

'pass' (파이썬의 noop 문) 대신'계속'해야합니까? 루프 외부의'continue' 문은 Python 2.7에서 SyntaxError입니다 (예외 처리 블록은 루프가 아닙니다). –

1

의 URL은 HTML 페이지로 리디렉션합니다. (이런 일을 확인하려면 curl을 사용하십시오.)

HTML 페이지는 분명히 JSON으로 파싱 될 수 없습니다.

은 당신이 아마 필요한 것은 이것이다 :

response = fetch_the_url(url) 
if response.status == 200: 
    try: 
    j1 = json.loads(response.text) 
    except ValueError: 
    # json can't be parsed 
    continue 
관련 문제