在python 3中用urllib打开一个url

Bra*_*ain 18 python url urllib python-3.x

我正在尝试从阳光基础打开此API的URL,并从json中的页面返回数据.这是我生成的代码,减去myapikey周围的括号.

import urllib.request.urlopen
import json

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

我得到这个错误

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

我究竟做错了什么?香港专业教育学院研究了https://docs.python.org/3/library/urllib.request.html仍然没有进展

sty*_*ane 27

您需要使用from urllib.request import urlopen,我建议您with在打开连接时使用该语句.

from urllib.request import urlopen

with urlopen("https://sunlightlabs.github.io/congress/legislators?api_key='(myapikey)") as conn:
    # dosomething
Run Code Online (Sandbox Code Playgroud)

  • @ BradleyD.Freeman-Bain:没有以下代码块,您将无法使用`with`语句。为了避免`SyntaxError`,添加任何代码,即使`pass`也可以。 (3认同)
  • 也许我还没有完全理解这个概念,但是对python来说还不是很新,但是一旦输入了您给定的代码,我就得到了第4行的缩进错误(以下空行为conn :),是否还有其他代码我应该用来遵循此规则?我不一定要你为我编写程序,但是任何资源将不胜感激。或gen 信息 (2认同)

Lyn*_*Lyn 7

在Python 3中,您可以这样实现:

import urllib.request
u = urllib.request.urlopen("xxxx")#The url you want to open
Run Code Online (Sandbox Code Playgroud)

注意: 有些IDE可以import urllib(Spyder)直接使用,而有些则需要import urllib.request(PyCharm).

那是因为你有时需要明确地导入你想要的部分,所以当你只需要一小部分时,模块不需要加载所有东西.

希望这会有所帮助.