我正在创建一个程序,它将通过读取在相同游戏/应用程序的.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')和字节(URL,encoding='utf-8'),但总是得到相同或类似的错误。
因此,基本上我的问题是,当URL以字符串类型存储时,如何从服务器下载文件?
发布于 2016-01-23 22:21:13
每当我想要一些与requests
请求相关的东西时,我都会使用HTTP包,因为它的接口非常容易上手:
首先,安装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)
发布于 2016-01-19 04:32:35
我希望我正确理解了这个问题:当URL以string类型存储时,如何从服务器下载文件?
我下载文件并使用以下代码将其保存在本地:
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()
发布于 2019-04-23 15:39:20
是的,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)
https://stackoverflow.com/questions/7243750
复制相似问题