我正在创建一个程序,将下载一个。jar (java)文件从一个web服务器,通过读取URL指定在同一游戏/应用程序的。jad文件。我使用的是Python 3.2.1

我已经设法从JAD文件中提取JAR文件的URL(每个JAD文件都包含到JAR文件的URL),但是正如您想象的那样,提取的值是type()字符串。

这是相关的函数:

def downloadFile(URL=None):
    import httplib2
    h = httplib2.Http(".cache")
    resp, content = h.request(URL, "GET")
    return content

downloadFile(URL_from_file)

然而,我总是得到一个错误,说在上面的函数的类型必须是字节,而不是字符串。我尝试使用URL.encode('utf-8'),也字节(URL,encoding='utf-8'),但我总是得到相同或类似的错误。

所以基本上我的问题是如何从服务器下载文件时,URL存储在字符串类型?


当前回答

是的,当然requests是一个很好的包,用于与HTTP请求相关的东西。但是我们需要注意输入数据的编码类型,下面是一个解释差异的示例


from requests import get

# case when the response is byte array
url = 'some_image_url'

response = get(url)
with open('output', 'wb') as file:
    file.write(response.content)


# case when the response is text
# Here unlikely if the reponse content is of type **iso-8859-1** we will have to override the response encoding
url = 'some_page_url'

response = get(url)
# override encoding by real educated guess as provided by chardet
r.encoding = r.apparent_encoding

with open('output', 'w', encoding='utf-8') as file:
    file.write(response.content)

其他回答

这里我们可以在Python3中使用urllib的Legacy接口:

下面的函数和类是从Python 2模块urllib(而不是urllib2)移植过来的。它们在将来的某个时候可能会被弃用。

示例(2行代码):

import urllib.request

url = 'https://www.python.org/static/img/python-logo.png'
urllib.request.urlretrieve(url, "logo.png")

你可以使用wget,一个流行的shell下载工具。https://pypi.python.org/pypi/wget 这将是最简单的方法,因为它不需要打开目标文件。这里有一个例子。

import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'  
wget.download(url, '/Users/scott/Downloads/cat4.jpg') 

如果你想获取一个网页的内容到一个变量中,只需要读取urllib.request.urlopen的响应:

import urllib.request
...
url = 'http://example.com/'
response = urllib.request.urlopen(url)
data = response.read()      # a `bytes` object
text = data.decode('utf-8') # a `str`; this step can't be used if data is binary

下载和保存文件最简单的方法是使用urllib.request.urlretrieve函数:

import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
urllib.request.urlretrieve(url, file_name)
import urllib.request
...
# Download the file from `url`, save it in a temporary directory and get the
# path to it (e.g. '/tmp/tmpb48zma.txt') in the `file_name` variable:
file_name, headers = urllib.request.urlretrieve(url)

但是请记住,urlretrieve被认为是遗留的,可能会被弃用(但不确定原因)。

因此,最正确的方法是使用urllib.request.urlopen函数返回一个表示HTTP响应的类文件对象,并使用shutil.copyfileobj将其复制到实际文件中。

import urllib.request
import shutil
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

如果这看起来太复杂,您可能想要更简单一点,将整个下载存储在一个bytes对象中,然后将其写入一个文件。但这只适用于小文件。

import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    data = response.read() # a `bytes` object
    out_file.write(data)

可以动态地提取.gz(或者其他格式)压缩数据,但是这样的操作可能需要HTTP服务器支持对文件的随机访问。

import urllib.request
import gzip
...
# Read the first 64 bytes of the file inside the .gz archive located at `url`
url = 'http://example.com/something.gz'
with urllib.request.urlopen(url) as response:
    with gzip.GzipFile(fileobj=response) as uncompressed:
        file_header = uncompressed.read(64) # a `bytes` object
        # Or do anything shown above using `uncompressed` instead of `response`.

我希望我正确理解了这个问题,即:当URL存储为字符串类型时,如何从服务器下载文件?

我下载文件并保存在本地使用下面的代码:

import requests

url = 'https://www.python.org/static/img/python-logo.png'
fileName = 'D:\Python\dwnldPythonLogo.png'
req = requests.get(url)
file = open(fileName, 'wb')
for chunk in req.iter_content(100000):
    file.write(chunk)
file.close()

如果你正在使用Linux,你可以通过python shell使用Linux的wget模块。下面是一个示例代码片段

import os
url = 'http://www.example.com/foo.zip'
os.system('wget %s'%url)