在 python 3 中用 urllib 打开 url

opening a url with urllib in python 3

我正在尝试从 sunlight foundation 打开这个 API 的 URL 和 json 中页面的 return 数据。这是我生成的代码,减去 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 但仍然没有进展

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

在 Python 3 你可以这样实现:

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

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

这是因为您有时需要显式导入所需的部分,因此当您只需要一小部分时,模块不需要加载所有内容。

希望这会有所帮助。

urllib.request 是一个模块,而 urlopen 是一个函数。 看看这个link,它可以帮你解开疑惑。 https://docs.python.org/3.0/library/urllib.request.html

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)

问题出在您的模块导入上。 在 Python3.x:

中有多种方法可以做到这一点
from urllib.request import urlopen
urlopen('example.com/***')

from urllib import request
request.urlopen('example.com/***')

import urllib
urllib.request.urlopen('example.com/***')

此外,您还可以命名要导入的模块:

import urllib.request as req  ## or whatever you want
req.urlopen('example.com/***')

您可以使用您喜欢的那个,但请注意您使用的模块和包的顺序。