Python lib执行错误

时间:2013-10-25 23:28:40

标签: python urllib2 urllib

我创建了这个python lib并且它使用了urllib和urllib2这个函数但是当我从python shell执行lib的函数时我得到了这个错误

>>> from sabermanlib import geturl
>>> geturl("roblox.com","ggg.html")

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    geturl("roblox.com","ggg.html")
  File "sabermanlib.py", line 21, in geturl
    urllib.urlretrieve(Address,File)
  File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 94, in urlretrieve
    return _urlopener.retrieve(url, filename, reporthook, data)
  File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 240, in retrieve
    fp = self.open(url, data)
  File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 208, in open
    return getattr(self, name)(url)
  File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 463, in open_file
    return self.open_local_file(url)
  File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 477, in open_local_file
    raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] The system cannot find the file specified: 'roblox.com'
>>>

这是lib i的代码:

import urllib
import urllib2




def geturl(Address,File):
    urllib.urlretrieve(Address,File)

编辑2

我无法理解为什么我在执行python shell时遇到这个错误:

geturl(Address,File)

1 个答案:

答案 0 :(得分:0)

你不想要urllib.urlretrieve。这需要一个类似文件的对象。相反,你想要urllib.urlopen:

>>> help(urllib.urlopen)
urlopen(url, data=None, proxies=None)
    Create a file-like object for the specified URL to read from.

此外,如果您想下载并保存文档,则需要更强大的geturl功能:

def geturl(Address, FileName):
    html_data = urllib.urlopen(Address).read()  # Open the URL
    with open(FileName, 'wb') as f:  # Open the file
        f.write(html_data)  # Write data from URL to file

geturl(u'http://roblox.com')  # URL's must contain the full URI, including http://