微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python请求库,发送帖子,获取,认证和下载文件

如何解决Python请求库,发送帖子,获取,认证和下载文件

我正在尝试自动下载许多发票。这些发票是由商店网站生成/存储的 pdf 文件。当前必须经历的“工作流程”如下所示:

1. Go to the website 
2. Login 
3. Possibly redirect to another URL (sometimes manually) 
4. Press a JScript button ("orders")
5. Press aonther JScript button ("download PDF") 
6. Repeat 5 for every PDF file that exists (invoice that exists) 

我想做的是使用 Python 3.9 + requests 库通过 API 自动将所有 PDF 文件下载到一个文件夹中。到目前为止,我已经设法使用 POST 成功登录 - 我知道这一点,因为每当我登录帐户时我都会收到一封电子邮件,所以当我运行我的脚本时,每当我应该登录时,我也会收到一封电子邮件。但是在这一点上我卡住。商店本身有一个 API(不是官方的),即使我可以成功登录,我似乎也无法从中获取(我收到 401 错误)。

我认为这是因为商店使用了我可以在浏览器中查看的访问令牌/cookie,但我不知道如何用我的脚本检索/发送它们。本店使用 OAUTH。是否有处理 OAUTH cookie/访问令牌的标准方法

这是我目前的脚本:

import requests
from bs4 import BeautifulSoup

s = requests.Session()

#URLS
url1= 'https://login.migros.ch/login'
url2= 'https://shop.migros.ch/shopping/public/v1/apI/Orders/ids'
url3= 'https://shop.migros.ch/customer/public/v1/api/users/self/reporting/INVOICE/en/orders/ORDERID(changed)'

#HEADERS GET + CSRF token
headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9','user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/80.0.3987.149 Safari/537.36'
    
}
get = s.get(url1,headers=headers,verify=False)

#print(get.text)


soup = BeautifulSoup(get.text,'lxml')
csrf_token = soup.select_one('Meta[name="_csrf"]')['content']
#print(csrf_token)


#LOGIN INFO
payload = {'username': 'myusername','password': 'mypassword','_csrf': csrf_token}

#HEADERS POST

post = s.post(url1,data=payload,verify=False)
#print(post.json)
#print(post.headers)
response = s.get(url1)
#print(response.headers)
get = s.get(url2,verify=False)
#print(get)

非常感谢任何帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。