2014-11-04 3 views
0

URL에서 읽는 python 코드가 있습니다.python에서 urllib.urlopen 연결을 닫는 방법

def submitTest(self,url): 
    response = None 
    if url is not None: 
     wptUrl = WebPageTestConfigUtils.getConfigValue('runTestURL')+"?f=json&url="+url+"&runs=3&video=1&web10=0&fvonly=1&mv=1&private=1&location=us_east_wptdriver:Chrome.DSL" 
     with closing(urllib.urlopen(wptUrl)) as response: 
      json.load(response) 
      return response["data"]["testId"] 

나는 문맥 lib 문서 https://docs.python.org/2/library/contextlib.html을 사용하여 파이썬 연결을 닫습니다. 하지만 다음 실행에 다음과 같은 오류가 발생합니다.

Traceback (most recent call last): 
File "webPageTestUtils.py", line 59, in <module> 
main() 
File "webPageTestUtils.py", line 56, in main 
print webPageTestProcessor.submitTest("www.amazon.com") 
File "webPageTestUtils.py", line 27, in submitTest 
return response["data"]["testId"] 
AttributeError: addinfourl instance has no attribute '__getitem__' 

내가 여기서 잘못하고있는 것. 나쁜 일이 생기거나 내가 그 일을 끝내면 연결을 닫을 방법이 필요합니다.

+0

가능한 중복 끝나면 연결을 닫습니다이 방법 (HTTP [내가 urllib.urlopen 후 close()를 호출해야합니다()를?] : // 유래. co.kr/questions/1522 –

답변

0

내가 여기서 잘못하고있는 것은 무엇입니까?
잡히지 않은 오류가 발생했습니다. 인용 @Nonnib에서 :

json.load는 당신이 필요로하는 개체를 반환하기 때문에

오류가 발생했습니다. 당신은 아마 찾고 있습니다 : response_dict = json.load (응답) 다음 response_dict [ "데이터"] [ "시험 ID"]

가능한 해결 반환 :
캐치 가능한 오류를 적절한 결과를 반환

def submitTest(self,url): 
    response = None 
    if url is not None: 
     wptUrl = WebPageTestConfigUtils.getConfigValue('runTestURL')+"?f=json&url="+url+"&runs=3&video=1&web10=0&fvonly=1&mv=1&private=1&location=us_east_wptdriver:Chrome.DSL" 
     with closing(urllib.urlopen(wptUrl)) as response: 
      json.load(response) 
      try: 
       return response["data"]["testId"] 
      except AttributeError: 
       return "an AttributeError occured" # or return something else, up to you 
      except: 
       return "an error occured" 

블록과 항상 정상적으로 실행하고이의

+0

아니요.하지만 처음에 오류가 발생했습니다. – station

+0

'response'는 dict이 아니기 때문에 –

+0

입니다.하지만 json.load를 사용하면 동일한 코드가 제대로 작동합니다. (urllib.urlopen (wptUrl)) – station

관련 문제