在 Python 中下载 Sharepoint Excel 文件

Sir*_*cam 5 python authentication rest excel sharepoint

我正在尝试使用 Python 脚本从 SharePoint 存储库下载 Excel 文件。我正在使用https://github.com/vgrem/Office365-REST-Python-Client示例中定义的 Office365-Rest-Python-Client ,我可以访问我需要的所有文件/目录。当我想下载任何文件时,问题就出现了。我尝试了几种方法,但没有一个有效:wget.download("https://shprepos.com/path/file.xlsx", local_path, bar=None)

但我收到“403 FORBIDDEN”错误。我也尝试过请求:

req = requests.get(ruta, auth=requests.auth.HTTPBasicAuth(username, password), headers=headers)
with open(local_file, 'wb') as file:
    file.write(req.content)
Run Code Online (Sandbox Code Playgroud)

使用此代码,我得到的是网页,而不是 excel 文件,我不明白为什么,因为如果我使用正确的身份验证访问 url“ https://shprepos.com/path/file.xlsx ”我下载文件。

您知道使用身份验证通过 wget 下载该文件的方法吗?或者我在 requests.get 中做错了什么?

我需要一种获取该文件的方法,使用我在脚本开头所做的先前身份验证:

ctx_auth = AuthenticationContext(shp_url)
token = ctx_auth.acquire_token_for_user(username, password)
Run Code Online (Sandbox Code Playgroud)

你知道这样做的方法吗?也许python客户端有下载文件的方法,但我找不到!

非常感谢!:)

问候

Sir*_*cam 3

是的!我找到了解决方案!我需要获得授权才能下载该文件。我在 Office365-Python-Client 的 test 文件夹中找到了一个示例。所以基本上,在获取带有请求的 url 之前,您需要获得授权:

options = RequestOptions(shp_file_path)
ctx_auth.authenticate_request(options)
options.headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f"
options.headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0)"
    req = requests.get(shp_file_path, headers=options.headers, verify=True, allow_redirects=True)
    if req.ok:
        with open(local_file, 'wb') as file:
            file.write(req.content)
Run Code Online (Sandbox Code Playgroud)

如果没有获取 auth_request 并添加标头,则无法获取该文件。

希望它能帮助将来的人,就像为我工作一样!任何改进都非常受欢迎!:)

  • 您能发布您使用的完整代码吗?我试图在这里做同样的事情,但没有运气。 (3认同)