【问题标题】:How to download a file with authentication?如何通过身份验证下载文件?
【发布时间】:2019-01-15 17:02:01
【问题描述】:

我正在使用网站“musescore.com”,该网站有许多“.mxl”格式的文件,我需要使用 Python 自动下载这些文件。

网站上的每个文件都有一个唯一的 ID 号。这是一个示例文件的链接:

https://musescore.com/user/43726/scores/76643

URL 中的最后一个数字是该文件的 ID 号。我不知道乐谱的 mxl 文件在网站上的哪个位置,但我知道要下载该文件,必须访问以下网址:

https://musescore.com/score/76643/download/mxl

此链接对于每个文件都是相同的,但其中包含该文件的特定 ID 号。据我了解,此 url 执行下载文件的代码,而不是文件的实际路径。

这是我的代码:

import requests

url = 'https://musescore.com/score/76643/download/mxl'
user = 'myusername'
password = 'mypassword'

r = requests.get(url, auth=(user, password), stream=True)
with open('file.mxl', 'wb') as f:
  for chunk in r.iter_content(chunk_size=1024):
    f.write(chunk)

此代码下载一个网页,说我需要登录才能下载文件。它应该为这个分数下载 mxl 文件。这一定意味着我对网站的身份验证不当。我该如何解决这个问题?

【问题讨论】:

    标签: python python-3.x authentication python-requests


    【解决方案1】:

    通过将auth 参数传递给get,您正在尝试使用HTTP Basic Authentication,这不是该特定站点使用的。您需要使用 request.Session 的实例发布到他们的登录端点并维护该过程产生的 cookie。

    此外,该站点使用了一个 csrf 令牌,您必须先从登录页面中提取该令牌,才能将其包含在您发到登录端点的帖子中。

    这是一个工作示例,显然您需要将用户名和密码更改为您自己的:

    import requests
    from bs4 import BeautifulSoup
    
    s = requests.Session()
    r = s.get('https://musescore.com/user/login')
    
    soup = BeautifulSoup(r.content, 'html.parser')
    csrf = soup.find('input', {'name': '_csrf'})['value']
    
    s.post('https://musescore.com/user/auth/login/process', data={
        'username': 'herp@derp.biz',
        'password': 'secret',
        '_csrf': csrf,
        'op': 'Log in'
    })
    
    r = s.get('https://musescore.com/score/76643/download/mxl')
    
    print(f"Status: {r.status_code}")
    print(f"Content-Type: {r.headers['content-type']}")
    

    结果,内容类型显示它正在成功下载文件:

    Status: 200
    Content-Type: application/vnd.recordare.musicxml
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-24
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多