如何使用Python和身份验证下载文件
我试图通过一个链接下载一个.tar文件,而不是直接指向该文件。如果浏览到该页面,弹出窗口显示“选择下载路径” url如下所示: 我是python新手 这是到目前为止我在项目这一部分的代码:如何使用Python和身份验证下载文件,python,download,tar,Python,Download,Tar,我试图通过一个链接下载一个.tar文件,而不是直接指向该文件。如果浏览到该页面,弹出窗口显示“选择下载路径” url如下所示: 我是python新手 这是到目前为止我在项目这一部分的代码: manager = urllib2.HTTPPasswordMgrWithDefaultRealm() manager.add_password(None, url, secrets["user"], secrets["password"]) #Create an authentication handle
manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, url, secrets["user"], secrets["password"])
#Create an authentication handler using the password manager
auth = urllib2.HTTPBasicAuthHandler(manager)
#Create an opener that will replace the default urlopen method on further calls
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)
#Here you should access the full url you wanted to open
response = urllib2.urlopen(url)
print response
打印响应将返回以下内容:
我不知道该怎么进一步,或者回答是否接近正确?我需要打开.tar并访问其中的raml文件,我不知道是需要下载并打开该文件,还是直接打开并打印出raml文件
有什么建议吗?您需要在
'wb'
模式下打开一个文件,并编写您试图下载的文件的内容,如下所示:
response = urllib2.urlopen(url)
with open(os.path.basename(url), 'wb') as wf:
wf.write(response.read())
您还可以指定路径,而不只是使用os.path.basename(url)
查看更多关于如何处理
.tar
文件的信息。当我收到一个包含HTML的文件时,请检查您的url
,您需要提供指向tar文件的链接。我没有也不能直接链接到.tar文件。