Python 2.7 中的 urllib.request

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3745771/
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-18 12:31:34  来源:igfitidea点击:

urllib.request in Python 2.7

pythontwittertweepy

提问by Dananjaya

I can use urllib.request module with Python 3.1. But when I execute the same program using Python 2.7, an error comes along the lines of;

我可以在 Python 3.1 中使用 urllib.request 模块。但是当我使用 Python 2.7 执行相同的程序时,会出现以下错误;

AttributeError: 'module' object has no attribute 'request'.

I believe this error is because theres no request module in urllib for Python 2.7. Because I need to use tweepyi'll have to stick with Python 2.7 since tweepy does not support Python 3.

我相信这个错误是因为 Python 2.7 的 urllib 中没有请求模块。因为我需要使用tweepy,所以我必须坚持使用 Python 2.7,因为 tweepy 不支持 Python 3。

So how I can use urllib.request module in Python 2.7?

那么如何在 Python 2.7 中使用 urllib.request 模块呢?

采纳答案by SilentGhost

回答by Greg S

Take a look at http://docs.python.org/library/urllib2.html.

看看http://docs.python.org/library/urllib2.html

The urllib2module is the predecessor to urllib.request/urllib.error(it has been split into those modules in Python 3.0).

urllib2模块是urllib.request/的前身urllib.error(它已在 Python 3.0 中拆分为这些模块)。

回答by jellyfish

It is also possible to use sixmodule to make code for both python2 & python3:

也可以使用six模块为 python2 和 python3 编写代码:

from six.moves import urllib
# ...
result = urllib.request.urlopen(url)