在python 3中用urllib打开一个url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36965864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:36:39  来源:igfitidea点击:

opening a url with urllib in python 3

pythonpython-3.xurlurllib

提问by Bradley D. Freeman-Bain

i'm trying to open the URL of this API from the sunlight foundation and return the data from the page in json. this is the code Ive produced, minus the parenthesis around myapikey.

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

import urllib.request.urlopen
import json

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

and im getting this error

我收到这个错误

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

what am i doing wrong? ive researched into https://docs.python.org/3/library/urllib.request.htmland still no progress

我究竟做错了什么?我研究了https://docs.python.org/3/library/urllib.request.html仍然没有进展

回答by styvane

You need to use from urllib.request import urlopen, also I suggest you use the withstatement while opening a connection.

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

回答by Lyn

In Python 3 You can implement that this way:

在 Python 3 中,您可以通过以下方式实现:

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

Pay attention:Some IDE can import urllib(Spyder) directly, while some need to import urllib.request(PyCharm).

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

That's because you sometimes need to explicitly import the pieces you want, so the module doesn't need to load everything up when you just want a small part of it.

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

Hope this will help.

希望这会有所帮助。

回答by Arnav Singh

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)

回答by Fazil Ahmed

urllib.requestis a module whereas urlopenis a function. check out this link, it can help you clear your doubts. https://docs.python.org/3.0/library/urllib.request.html

urllib.request是一个模块而是urlopen一个函数。查看此链接,它可以帮助您消除疑虑。 https://docs.python.org/3.0/library/urllib.request.html