-1

我制作了这个 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的代码:

import urllib
import urllib2




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

编辑 2

我不明白为什么我在执行 python shell 时收到此错误:

geturl(Address,File)
4

1 回答 1

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://
于 2013-10-25T23:35:24.113 回答