파이썬 3에서 urllib로 URL 열기

선라이트 재단에서 이 API의 URL을 열고 페이지의 데이터를 json으로 반환하려고 합니다. 이것은 제가 만든 코드이며, myapikey 주위의 괄호를 뺀 것입니다.

import urllib.request.urlopen
import json

urllib.request.urlopen("https://sunlightlabs.github.io/congress/legislators?api_key='(myapikey)")

이 오류가 발생합니다.

Traceback (most recent call last):
  File "<input>", line 1, in <module>
ImportError: No module named request.urlopen

내가 뭘 잘못하고 있나요? https://docs.python.org/3/library/urllib.request.html 을 조사했지만 여전히 진전이 없습니다.

해결책

urllib.request에서 urlopen 가져오기를 사용해야 하며, 연결을 여는 동안와` 문을 사용하는 것이 좋습니다.

from urllib.request import urlopen

with urlopen("https://sunlightlabs.github.io/congress/legislators?api_key='(myapikey)") as conn:
    # dosomething
해설 (2)

파이썬 3에서는 다음과 같은 방법으로 구현할 수 있습니다:

import urllib.request
u = urllib.request.urlopen("xxxx")#The url you want to open

주의: 일부 IDE는 urllib(스파이더)를 직접 임포트할 수 있지만, 일부는 임포트 urllib.request(파이참)를 사용해야 합니다.

이는 원하는 부분만 명시적으로 가져와야 하는 경우가 있기 때문에 모듈의 일부만 필요할 때 모든 모듈을 로드할 필요가 없기 때문입니다.

도움이 되길 바랍니다.

해설 (0)
from urllib.request import urlopen
from bs4 import BeautifulSoup

wiki = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"

page = urlopen(wiki)
soup =  BeautifulSoup(page, "html.parser" ).encode('UTF-8')

print (soup)
해설 (1)

'urllib.request'는 모듈이고 'urlopen'은 함수입니다. 이 링크를 확인하면 의문을 해소하는 데 도움이 될 수 있습니다. https://docs.python.org/3.0/library/urllib.request.html

해설 (1)