我正在创建一个程序,该程序将通过读取同一游戏/应用程序的 .jad 文件中指定的 URL,从 Web 服务器下载 .jar (java) 文件。我正在使用 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') 和 bytes(URL,encoding='utf-8'),但我总是会遇到相同或类似的错误。
所以基本上我的问题是,当 URL 以字符串类型存储时,如何从服务器下载文件?
最佳答案
如果要获取网页内容到变量中,只需读取
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
被视为 legacy并且可能会被弃用(但不知道为什么)。
所以最正确的方法是使用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`.
https://stackoverflow.com/questions/7243750/
相关文章:
python - PEP8 的 E128 : continuation line under-ind
python - 如何从 Python 中的线程获取返回值?
javascript - 当您将 Selenium 与 chromedriver 一起使用时,网站可
python - 从 Django QuerySet 获取 SQL
python - 如何使用 Flask 从 URL 获取命名参数?
python - 如何在 Python 中获取当前模块中所有类的列表?
python - 将标准输出重定向到 Python 中的文件?