模拟登陆 发表于 2022-03-14 | 分类于 python爬虫 Cookie和Session123456789101112131415161718192021222324# 方式一# requests会自动保存每次请求后设置的Cookie,下次请求自动带上session = requests.Session()session.post(LOGIN_URL, data={ 'username': USERNAME, 'password': PASSWORD})response_index = session.get(INDEX_URL)# 方式二# 采用Selenium模拟登陆保存Cookiebrowser = webdriver.Chrome()browser.get(BASE_URL)browser.find_element_by_css_selector('input[name="username"]').send_keys(USERNAME)browser.find_element_by_css_selector('input[name="password"]').send_keys(PASSWORD)browser.find_element_by_css_selector('input[type="submit"]').click()time.sleep(10)cookies = browser.get_cookies()browser.close()session = requests.Session()# 唯一需要注意的是:Selenium获取的Cookie需要设置进session中for cookie in cookies: session.cookies.set(cookie['name'], cookie['value'])response_index = session.get(INDEX_URL) JWT登陆123456789101112session = requests.Session()response_login = session.post(LOGIN_URL, data={ 'username': USERNAME, 'password': PASSWORD})jwt = response_login.json().get('token')headers = { 'Authorization': f'jwt {jwt}'}response = requests.get(INDEX_URL, params={'limit': 18, 'offset': 0}, headers=headers) 赏个🍗吧 打赏 微信支付 支付宝 本文作者: Keeep 本文链接: http://Keeep.coding.me/blog/模拟登陆-1/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!