我正在使用Python Requests libray登录网站。为此,我需要捕获登录页面的一些数据,然后使用它向同一页面发出POST请求。
我的第一种方法是:
import requests
from bs4 import BeautifulSoup
from contextlib import contextmanager
def get_data(soup, ids, **kwargs):
pass
@contextmanager
def login_session(username='user', password='pass'):
auth = {'username': username, 'password': password}
url = 'http://example.com/Login.aspx'
ids = ('#this', '#other')
with requests.Session() as s:
soup = BeautifulSoup(s.get(url).content)
s.post(url, data=get_data(soup, ids, **auth))
yield s
with login_session() as s:
page = s.get('http://example/protected.aspx').content
但是,我发现请求提供BaseAuth
课程来制作custom authentication。
所以,我尝试实现自己的CustomAuth
import requests
class CustomAuth(AuthBase):
ids = ('#this', '#other')
url = "http://example.com/Login.aspx"
def __init__(self, username, password):
self.username = username
self.password = password
def _get_data(self, soup):
pass
def __call__(self, r):
'''Prepare data for POST request'''
with requests.Session() as s:
soup = BeautifulSoup(s.get(self.url).content)
r.data = self._get_data(soup)
return r
with requests.Session() as s:
s.post(CustomAuth.url, auth=CustomAuth('user','pass'))
但它没有按预期工作。
那么,是否可以在这种情况下使用BaseAuth
?