在 python 3 中使用 urllib 打开一个 url

新手上路,请多包涵

我正在尝试从 sunlight foundation 打开此 API 的 URL,并以 JSON 格式从页面返回数据。这是我生成的代码,减去我的 API 密钥周围的括号。

 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 仍然没有进展。

原文由 Bradley D. Freeman-Bain 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 541
2 个回答

您需要使用 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

原文由 styvane 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 Python 3 中你可以这样实现:

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

注意: 有的IDE可以直接 import urllib (Spyder),有的则需要 import urllib.request (PyCharm)。

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

希望这会有所帮助。

原文由 Lyn 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题