用Python 3从web下载文件

2024-04-20 04:11:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我已经成功地从JAD文件中提取了JAR文件的URL(每个JAD文件都包含JAR文件的URL),但是正如您所想象的,提取的值是type()string。

相关功能如下:

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')和bytes(URL,encoding='utf-8'),但总是会得到相同或类似的错误。

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


Tags: 文件字符串程序服务器应用程序游戏url类型
3条回答

如果要将网页内容获取为变量,只需read的响应^{}

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

下载和保存文件的最简单方法是使用^{}函数:

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被认为是legacy,可能会被弃用(但不确定原因)。

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

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()

每当需要与HTTP请求相关的东西时,我都会使用requests包,因为它的API很容易启动:

首先,安装requests

$ pip install requests

那么代码:

from requests import get  # to make GET request


def download(url, file_name):
    # open in binary mode
    with open(file_name, "wb") as file:
        # get request
        response = get(url)
        # write to file
        file.write(response.content)

相关问题 更多 >