在python 3中使用urllib打开url

2024-06-02 15:48:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从阳光基金会打开这个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,但仍然没有进展


Tags: 数据代码httpsimportapijsonurlrequest
3条回答
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)

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

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

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

这是因为有时需要显式地导入所需的片段,所以当只需要其中一小部分时,模块不需要加载所有内容。

希望这会有帮助。

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

相关问题 更多 >