0

我正在尝试学习 Python,并且正在尝试学习模块。我使用的 Python 版本是 Python 2.7.4。我试图学习的模块是 urllib。但是,每当我尝试运行下面的代码时,都会收到一个名为“无导入命名请求”的错误。代码如下。

import urllib.request

class App():
    def main(self):
        inp = raw_input('Please enter a string\n')
        print(inp)
        inp = input('Please enter a value\n')
        print(inp)

if __name__ == '__main__':
    App().main()

然后我尝试使用 urllib2。所以我改变了第一行

import urllib2

但随后它说'IndentationError:期望一个缩进块'。但如果我写

import urllib

那么我没有得到任何错误。但是我不能使用该库的任何功能。

4

2 回答 2

1

urllib.request适用于 Python 3。对于 Python 2,您需要执行以下操作:

from urllib import urlopen

或者使用urllib2模块:

from urllib2 import urlopen

你不应该得到一个IndentationError,但你可能犯了一些小错误。

于 2013-08-17T03:14:11.803 回答
1

这是python2.7的简单沙盒实现:

import urllib

def main():
    #one indentation level
    print urllib.urlopen("http://stackoverflow.com").read ()

if __name__ == '__main__': main()

如果此代码运行而您的代码没有运行,则问题不在于导入/使用 urllib。它使用 pthon2.7.4 在我的机器上运行。

替代版本:

from urllib import urlopen

def main():
    #one indentation level
    print urlopen("http://stackoverflow.com").read ()

if __name__ == '__main__': main()

或使用您的App-Class

import urllib

class App:
    def main(self):
        print urllib.urlopen("http://stackoverflow.com").read ()

if __name__ == '__main__':
    App().main()
于 2013-08-17T03:36:51.230 回答