- cookie的获取
import requests url = 'http://example.com' resp = requests.get(url) # cookie的返回与字典行为类似,但不是字典 cookie_element_value = resp.cookies['cookie_element_key']
import requests con = requests.Session() resp = con.get("this is an https url", verify=False) # 通过requests自带工具完成cookie的获取和字典化 cookie = requests.utils.dict_from_cookiejar(resp.cookies) params="Here is the data you want to send" # 将获取到的cookie在后续的发送中使用 next_resp = con.post("this is a new https url", params, cookies=cookie, verify=False)
- 在请求中发送cookie
import requests url = 'http://example.com' # 此处构建的cookies最终形式为 {'cookies_are':'working'} cookies = dict(cookies_are='working') resp = requests.get(url, cookies=cookies)
- RequestsCookieJar
import requests # Cookie 的返回对象为 RequestsCookieJar,它的行为和字典类似,但接口更为完整,适合跨域名跨路径用。# 还可以把 Cookie Jar 传到 Requests 中 jar = requests.cookies.RequestsCookieJar() jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies') jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere') url = 'http://httpbin.org/cookies' resp = requests.get(url, cookies=jar)
使用requests测试接口时获取cookie
最新推荐文章于 2024-05-10 06:41:24 发布