# 3.2.2 高级用法
## 1. 文件上传 {#1-文件上传}
利用requests实现文件上传
实例:
```text
import requests
files = {'file':open('favicon.ico','rb')}
response = requests.post('http://httpbin.org/post',files=files)
print(response.text)
```
运行结果:
```text
{
"args": {},
"data": "",
"files": {
"file": "data:application/octet-stream;base64,AAABAAIAEBAAAAEAIAAoBQAAJgAAACAgAAABACAAKBQAAE4FAAAoAAAAEAAAACAAAAABACAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABERE3YTExPFDg4OEgAAAAAAAAAADw8PERERFLETExNpAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQUFJYTExT8ExMU7QAAABkAAAAAAAAAAAAAABgVFRf/FRUX/xERE4UAAAAAAAAAAAAAAAAAAAAAAAAAABEREsETExTuERERHhAQEBAAAAAAAAAAAAAAAAAAAAANExMU9RUVF/8VFRf/EREUrwAAAAAAAAAAAAAAABQUFJkVFRf/BgYRLA4ODlwPDw/BDw8PIgAAAAAAAAAADw8PNBAQEP8VFRf/FRUX/xUVF/8UFBSPAAAAABAQEDAPDQ//AAAA+QEBAe0CAgL/AgIC9g4ODjgAAAAAAAAAAAgICEACAgLrFRUX/xUVF/8VFRf/FRUX/xERES0UFBWcFBQV/wEBAfwPDxH7DQ0ROwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0NEjoTExTnFRUX/xUVF/8SEhKaExMT2RUVF/8VFRf/ExMTTwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAERERTBUVF/8VFRf/ExMT2hMTFPYVFRf/FBQU8AAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAITExTxFRUX/xMTFPYTExT3FRUX/xQUFOEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFBQU4RUVF/8TExT3FBQU3hUVF/8TExT5Dw8PIQAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "6665",
"Content-Type": "multipart/form-data; boundary=6790c78bd178438aa1f006feb3faf802",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "220.197.208.229",
"url": "http://httpbin.org/post"
}
```
## 2. Cookies {#2-cookies}
设置cookies实例:
```text
import requests
response = requests.get('https://www.baidu.com')
print(response.cookies)
for key,value in response.cookies.items():
print(key+"="+value)
```
运行结果:
```text
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ=27315
```
返回的是RequestCookieJar 类型
以知乎为例,直接利用 Cookies 来维持登录状态
```text
import requests
headers = {
'Cookie': 'q_c1=31653b264a074fc9a57816d1ea93ed8b|1474273938000|1474273938000; d_c0="AGDAs254kAqPTr6NW1U3XTLFzKhMPQ6H_nc=|1474273938"; __utmv=51854390.100-1|2=registration_date=20130902=1^3=entry_date=20130902=1;a_t="2.0AACAfbwdAAAXAAAAso0QWAAAgH28HQAAAGDAs254kAoXAAAAYQJVTQ4FCVgA360us8BAklzLYNEHUd6kmHtRQX5a6hiZxKCynnycerLQ3gIkoJLOCQ==";z_c0=Mi4wQUFDQWZid2RBQUFBWU1DemJuaVFDaGNBQUFCaEFsVk5EZ1VKV0FEZnJTNnp3RUNTWE10ZzBRZFIzcVNZZTFGQmZn|1474887858|64b4d4234a21de774c42c837fe0b672fdb5763b0',
'Host': 'www.zhihu.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
}
r = requests.get('https://www.zhihu.com', headers=headers)
print(r.text)
```
运行结果:
```text
<!doctype html>
<html lang="zh" data-hairline="true" data-theme="light"><head><meta charSet="utf-8"/><title data-react-helmet="true">知乎 - 发现更大的世界</title><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"/><meta name="renderer" content="webkit"/><meta name="force-rendering" content="webkit"/><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/><meta name="google-site-verification" content="FTeR0c8arOPKh8c5DYh_9uu98_zJbaWw53J-Sch9MTg"/><link rel="shortcut icon" type="image/x-icon" href="https://static.zhihu.com/static/favicon.ico"/><link rel="search" type="application/opensearchdescription+xml" href="https://static.zhihu.com/static/search.xml" title="知乎"/><link rel="dns-prefetch" href="//static.zhimg.com"/><link rel="dns-prefetch" href="//pic1.zhimg.com"/><link rel="dns-prefetch" href="//pic2.zhimg.com"/><link rel="dns-prefetch" href="//pic3.zhimg.com"/><link rel="dns-prefetch" href="//pic4.zhimg.com"/><link href="https://static.zhihu.com/heifetz/main.app.efada145308ef5d626df.css" rel="stylesheet"/></head><body class="EntrySign-body Body--isAppleDevice"><p hidden="">有问题,上知乎。知乎作为中文互联网最大的知识分享平台,以「知识连接一切」为愿景,致力于构建一个人人都可以便捷接入的知识分享网络,让人们便捷地与世界分享知识、经验和见解,发现更大的世界。</p><div id="root"><div data-zop-usertoken="{}" data-reactroot=""><div class="LoadingBar"></div><div><header role="banner" class="Sticky AppHeader" data-za-module="TopNavBar"><div class="AppHeader-inner"><a href="//www.zhihu.com" aria-label="知乎"><svg viewBox="0 0 200 91" class="Icon ZhihuLogo ZhihuLogo--blue Icon--logo" style="height:30px;width:64px" width="64" height="30" aria-hidden="true"><title></title><g><path d="M53.29 80.035l7.32.002 2.41 8.24 13.128-8.24h15.477v-67.98H53.29v67.978zm7.79-60.598h22.756v53.22h-8.73l-8.718 5.473-1.587-5.46-3.72-.012v-53.22zM46.818 43.162h-16.35c.545-8.467.687-16.12.687-22.955h15.987s.615-7.05-2.68-6.97H16.807c1.09-4.1 2.46-8.332 4.1-12.708 0 0-7.523 0-10.085 6.74-1.06 2.78-4.128 13.48-9.592 24.41 1.84-.2 7.927-.37 11.512-6.94.66-1.84.785-2.08 1.605-4.54h9.02c0 3.28-.374 20.9-.526 22.95H6.51c-3.67 0-4.863 7.38-4.863 7.38H22.14C20.765 66.11 13.385 79.24 0 89.62c6.403 1.828 12.784-.29 15.937-3.094 0 0 7.182-6.53 11.12-21.64L43.92 85.18s2.473-8.402-.388-12.496c-2.37-2.788-8.768-10.33-11.496-13.064l-4.57 3.627c1.363-4.368 2.183-8.61 2.46-12.71H49.19s-.027-7.38-2.372-7.38zm128.752-.502c6.51-8.013 14.054-18.302 14.054-18.302s-5.827-4.625-8.556-1.27c-1.874 2.548-11.51 15.063-11.51 15.063l6.012 4.51zm-46.903-18.462c-2.814-2.577-8.096.667-8.096.667s12.35 17.2 12.85 17.953l6.08-4.29s-8.02-11.752-10.83-14.33zM199.99 46.5c-6.18 0-40.908.292-40.953.292v-31.56c1.503 0 3.882-.124 7.14-.376 12.773-.753 21.914-1.25 27.427-1.504 0 0 3.817-8.496-.185-10.45-.96-.37-7.24 1.43-7.24 1.43s-51.63 5.153-72.61 5.64c.5 2.756 2.38 5.336 4.93 6.11 4.16 1.087 7.09.53 15.36.277 7.76-.5 13.65-.76 17.66-.76v31.19h-41.71s.88 6.97 7.97 7.14h33.73v22.16c0 4.364-3.498 6.87-7.65 6.6-4.4.034-8.15-.36-13.027-.566.623 1.24 1.977 4.496 6.035 6.824 3.087 1.502 5.054 2.053 8.13 2.053 9.237 0 14.27-5.4 14.027-14.16V53.93h38.235c3.026 0 2.72-7.432 2.72-7.432z" fill-rule="evenodd"/></g></svg></a><nav role="navigation" class="AppHeader-nav"><a class="AppHeader-navItem" href="//www.zhihu.com/">首页</a><a class="AppHeader-navItem" href="//www.zhihu.com/explore">发现</a><a href="//www.zhihu.com/topic" class="AppHeader-navItem">话题</a></nav><div class="SearchBar" role="search" data-za-module="PresetWordItem"><div class="SearchBar-toolWrapper"><form class="SearchBar-tool"><div><div class="Popover"><div class="SearchBar-input Input-wrapper Input-wrapper--grey"><input type="text" maxLength="100" value="" autoComplete="off" role="combobox" aria-expanded="false" aria-autocomplete="list" aria-activedescendant="null--1" id="null-toggle" aria-haspopup="true" aria-owns="null-content" class="Input" placeholder=""/><div class="Input-after"><button aria-label="搜索" type="button" class="Button SearchBar-searchIcon Button--primary"><svg viewBox="0 0 16 16" class="Icon Icon--search" style="height:16px;width:16px" width="16" height="16" aria-hidden="true"><title></title><g><path d="M12.054 10.864c.887-1.14 1.42-2.57 1.42-4.127C13.474 3.017 10.457 0 6.737 0S0 3.016 0 6.737c0 3.72 3.016 6.737 6.737 6.737 1.556 0 2.985-.533 4.127-1.42l3.103 3.104c.765.46 1.705-.37 1.19-1.19l-3.103-3.104zm-5.317.925c-2.786 0-5.053-2.267-5.053-5.053S3.95 1.684 6.737 1.684 11.79 3.95 11.79 6.737 9.522 11.79 6.736 11.79z"/></g></svg></button></div></div></div></div></form></div></div><div class="AppHeader-userInfo"><div><button type="button" class="Button AppHeader-login Button--blue">登录</button><button type="button" class="Button Button--primary Button--blue">加入知乎</button></div></div></div></header></div><main role="main" class="App-main"><div class="SignFlowHomepage"><div class="SignFlowHomepage-content"><div class="Card SignContainer-content"><div class="SignFlowHeader" style="padding-bottom:5px"><svg viewBox="0 0 200 91" class="Icon ZhihuLogo ZhihuLogo--blue Icon--logo" style="height:65.625px;width:140px" width="140" height="65.625" aria-hidden="true"><title></title><g><path d="M53.29 80.035l7.32.002 2.41 8.24 13.128-8.24h15.477v-67.98H53.29v67.978zm7.79-60.598h22.756v53.22h-8.73l-8.718 5.473-1.587-5.46-3.72-.012v-53.22zM46.818 43.162h-16.35c.545-8.467.687-16.12.687-22.955h15.987s.615-7.05-2.68-6.97H16.807c1.09-4.1 2.46-8.332 4.1-12.708 0 0-7.523 0-10.085 6.74-1.06 2.78-4.128 13.48-9.592 24.41 1.84-.2 7.927-.37 11.512-6.94.66-1.84.785-2.08 1.605-4.54h9.02c0 3.28-.374 20.9-.526 22.95H6.51c-3.67 0-4.863 7.38-4.863 7.38H22.14C20.765 66.11 13.385 79.24 0 89.62c6.403 1.828 12.784-.29 15.937-3.094 0 0 7.182-6.53 11.12-21.64L43.92 85.18s2.473-8.402-.388-12.496c-2.37-2.788-8.768-10.33-11.496-13.064l-4.57 3.627c1.363-4.368 2.183-8.61 2.46-12.71H49.19s-.027-7.38-2.372-7.38zm128.752-.502c6.51-8.013 14.054-18.302 14.054-18.302s-5.827-4.625-8.556-1.27c-1.874 2.548-11.51 15.063-11.51 15.063l6.012 4.51zm-46.903-18.462c-2.814-2.577-8.096.667-8.096.667s12.35 17.2 12.85 17.953l6.08-4.29s-8.02-11.752-10.83-14.33zM199.99 46.5c-6.18 0-40.908.292-40.953.292v-31.56c1.503 0 3.882-.124 7.14-.376 12.773-.753 21.914-1.25 27.427-1.504 0 0 3.817-8.496-.185-10.45-.96-.37-7.24 1.43-7.24 1.43s-51.63 5.153-72.61 5.64c.5 2.756 2.38 5.336 4.93 6.11 4.16 1.087 7.09.53 15.36.277 7.76-.5 13.65-.76 17.66-.76v31.19h-41.71s.88 6.97 7.97 7.14h33.73v22.16c0 4.364-3.498 6.87-7.65 6.6-4.4.034-8.15-.36-13.027-.566.623 1.24 1.977 4.496 6.035 6.824 3.087 1.502 5.054 2.053 8.13 2.053 9.237 0 14.27-5.4 14.027-14.16V53.93h38.235c3.026 0 2.72-7.432 2.72-7.432z" fill-rule="evenodd"/></g></svg><div class="SignFlowHeader-slogen">登录<!-- -->知乎,发现更大的世界</div></div><div class="SignContainer-inner"><div class="Login-content"><form novalidate="" class="SignFlow"><div class="SignFlow-account"><div class="SignFlow-supportedCountriesSelectContainer"></div><div class="SignFlowInput SignFlow-accountInputContainer"><div class="SignFlow-accountInput Input-wrapper"><input type="text" value="" name="username" class="Input" placeholder="手机号或邮箱"/></div><div class="SignFlowInput-errorMask SignFlowInput-requiredErrorMask SignFlowInput-errorMask--hidden"></div></div></div><div class="SignFlow-password"><div class="SignFlowInput"><div class="Input-wrapper"><input type="password" value="" name="password" class="Input" placeholder="密码"/></div><div class="SignFlowInput-errorMask SignFlowInput-requiredErrorMask SignFlowInput-errorMask--hidden"></div></div><button tabindex="-1" type="button" class="Button SignFlow-switchPassword Button--plain"><svg width="24" height="20" viewBox="0 0 24 24" class="Icon SignFlow-switchPasswordIcon Icon--inconspicuous" style="vertical-align:middle;height:20px;width:24px" aria-hidden="true"><title></title><g><title>Inconspicuous</title><path d="M17.007 11.504c0 .65-.13 1.26-.36 1.83l3 3.073S23 14.136 23 11.504C23 8.008 17.255 4 11.995 4c-1.4 0-2.741.25-3.982.701l2.161 2.16c.57-.23 1.18-.36 1.831-.36a5.004 5.004 0 0 1 5.002 5.003zM2.57 4.342l2.067 2.075C3.499 7.258 1 9.119 1 11.504c0 3.336 5.79 7.503 11.005 7.503 1.55 0 3.031-.3 4.382-.84l.42.42 2.125 2.118s.782.571 1.314 0-.074-1.305-.074-1.305L3.955 3.183s-.76-.742-1.385-.19c-.626.554 0 1.35 0 1.35zm4.963 4.96l1.55 1.552c-.05.21-.08.43-.08.65 0 1.66 1.341 3.001 3.002 3.001.22 0 .44-.03.65-.08l1.551 1.551c-.67.33-1.41.53-2.2.53a5.004 5.004 0 0 1-5.003-5.002c0-.79.2-1.53.53-2.201zm4.312-.78l3.151 3.152.02-.16c0-1.66-1.34-3.001-3.001-3.001l-.17.01z" fill-rule="evenodd"/></g></svg></button></div><div class="Captcha SignFlow-captchaContainer" style="width:0;height:0;opacity:0;overflow:hidden;margin:0;padding:0;border:0"><div><div class="Captcha-chineseOperator"><span class="Captcha-info">请点击图中倒立的文字</span><button type="button" class="Button Captcha-chineseRefreshButton Button--plain"><svg class="Zi Zi--Refresh" fill="currentColor" viewBox="0 0 24 24" width="20" height="20"><path d="M20 12.878C20 17.358 16.411 21 12 21s-8-3.643-8-8.122c0-4.044 3.032-7.51 6.954-8.038.034-1.185.012-1.049.012-1.049-.013-.728.461-1.003 1.057-.615l3.311 2.158c.598.39.596 1.026 0 1.418l-3.31 2.181c-.598.393-1.08.12-1.079-.606 0 0 .006-.606-.003-1.157-2.689.51-4.675 2.9-4.675 5.708 0 3.21 2.572 5.822 5.733 5.822 3.163 0 5.733-2.612 5.733-5.822 0-.633.51-1.148 1.134-1.148.625 0 1.133.515 1.133 1.148" fill-rule="evenodd"></path></svg></button></div><div class="Captcha-chineseContainer"><img data-tooltip="看不清楚?换一张" class="Captcha-chineseImg" src="data:image/jpg;base64,null" alt="图形验证码"/></div></div></div><div class="Login-options"><button type="button" class="Button Login-switchType Button--plain">手机验证码登录</button><button type="button" class="Button Login-cannotLogin Button--plain">忘记密码?</button></div><button type="submit" class="Button SignFlow-submitButton Button--primary Button--blue">登录</button><div class="Login-footer"><span class="Login-qrcode"><button type="button" class="Button Button--plain">二维码登录</button></span><span class="Login-footerSeparate Login-qrcodeSeparate"> · </span><span class="Login-aboardPhone"><button type="button" class="Button Button--plain">海外手机登录</button></span><span class="Login-footerSeparate"> · </span><span class="Login-socialLogin"><button type="button" class="Button Login-socialButtonEntrance Button--plain">社交帐号登录</button><span class="Login-socialButtonGroup Login-socialButtonGroup--hidden"><button disabled="" type="button" class="Button Login-socialButton Button--plain"><svg viewBox="0 0 20 19" class="Icon Login-socialIcon Icon--wechat" style="height:17px;width:18px" width="18" height="17" aria-hidden="true"><title></title><g><path fill-rule="evenodd" d="M.224 18.667s4.24-1.825 4.788-2.056C13.03 20.14 20 14.715 20 8.9 20 3.984 15.523 0 10 0S0 3.984 0 8.898c0 1.86.64 3.585 1.737 5.013-.274.834-1.513 4.757-1.513 4.757zM6.167 8.96c.69 0 1.25-.57 1.25-1.27 0-.703-.56-1.272-1.25-1.272s-1.25.57-1.25 1.27c0 .703.56 1.272 1.25 1.272zm7.583 0c.69 0 1.25-.57 1.25-1.27 0-.703-.56-1.272-1.25-1.272s-1.25.57-1.25 1.27c0 .703.56 1.272 1.25 1.272z"/></g></svg></button><button disabled="" type="button" class="Button Login-socialButton Button--plain"><svg viewBox="0 0 22 18" class="Icon Login-socialIcon Icon--weibo" style="height:16px;width:20px" width="20" height="16" aria-hidden="true"><title></title><g><g fill-rule="evenodd"> <path d="M14.518.06s-.87.644.03 1.71c0 0 6.287-1.19 5.69 6.33 0 0 1.05 1.13 1.674-.31 0 .002 1.44-8.584-7.394-7.73zM4.883 13.17s.038 2.584 3.326 2.584c3.657 0 3.683-2.98 3.683-2.98S12.1 9.67 8.687 9.61c-3.863-.07-3.804 3.56-3.804 3.56zM7.41 14.21c-.668 0-1.214-.447-1.214-.998 0-.55.543-.998 1.215-.998.67 0 1.213.447 1.213.998 0 .55-.54.998-1.212.998z"/> <path d="M4.317 4.52C-2.603 10.353.873 14.85.873 14.85c.57 1.01 3.382 3.1 8.596 3.1 5.21 0 9.314-3.628 9.314-6.44 0-2.813-2.918-2.714-2.918-2.714 1.04-1.554.19-2.65.19-2.65-1.684-2.118-5.404-.16-5.407-.158.772-1.717.11-2.797.11-2.797C8.932.66 4.317 4.52 4.317 4.52zm10.448 7.79s-.467 4.16-6.447 4.16c-5.745 0-5.82-3.322-5.842-3.712 0 0-.073-4.423 6.58-4.654 5.94-.204 5.71 4.207 5.71 4.207zM18.65 7.045s1.018-4.37-3.864-3.818c0 0-.628.58.09 1.346 0 0 2.602-.58 2.397 2.598 0 0 .715.885 1.376-.125z"/> </g></g></svg></button><button disabled="" type="button" class="Button Login-socialButton Button--plain"><svg width="17" height="19" viewBox="0 0 18 20" xmlns="http://www.w3.org/2000/svg" class="Icon Login-socialIcon Icon--qq" style="height:19px;width:17px" aria-hidden="true"><title></title><g><title>QQ</title><path d="M9.003 0c-2.265 0-6.29 1.364-6.29 7.325V8.52S.55 12.96.55 15.474c0 .665.17 1.025.28 1.025.115 0 .903-.485 1.75-2.073 0 0-.18 2.197 1.903 3.967 0 0-1.77.495-1.77 1.182 0 .686 4.078.43 6.29 0 2.24.425 6.287.687 6.287 0 0-.688-1.768-1.182-1.768-1.182 2.085-1.77 1.905-3.967 1.905-3.967.845 1.588 1.634 2.072 1.746 2.072.11 0 .283-.36.283-1.026 0-2.514-2.166-6.954-2.166-6.954V7.325C15.29 1.365 11.268 0 9.003 0z" fill-rule="evenodd"/></g></svg></button></span></span></div></form></div><div class="SignContainer-switch">没有帐号?<span>注册</span></div><div class="SignFlowHomepage-qrImage SignFlowHomepage-qrImageHidden"><div></div></div></div></div><button type="button" class="Button SignFlowHomepage-downloadBtn">下载知乎 App</button></div><footer class="SignFlowHomepage-footer"><div class="ZhihuLinks"><a target="_blank" rel="noopener noreferrer" href="https://zhuanlan.zhihu.com">知乎专栏</a><a target="_blank" rel="noopener noreferrer" href="/roundtable">圆桌</a><a target="_blank" rel="noopener noreferrer" href="/explore">发现</a><a target="_blank" rel="noopener noreferrer" href="/app">移动应用</a><a target="_blank" rel="noopener noreferrer" href="/contact">联系我们</a><a target="_blank" rel="noopener noreferrer" href="https://app.mokahr.com/apply/zhihu">来知乎工作</a><a target="_blank" rel="noopener noreferrer" href="/org/signup">注册机构号</a></div><div class="ZhihuRights"><span>© 2018 知乎</span><a target="_blank" rel="noopener noreferrer" href="http://www.miibeian.gov.cn/">京 ICP 证 110745 号</a><span>京公网安备 11010802010035 号<a href="http://zhstatic.zhihu.com/assets/zhihu/publish-license.jpg" target="_blank" rel="noopener noreferrer">出版物经营许可证</a></span></div><div class="ZhihuReports"><a target="_blank" rel="noopener noreferrer" href="https://zhuanlan.zhihu.com/p/28852607">侵权举报</a><a target="_blank" rel="noopener noreferrer" href="http://www.12377.cn">网上有害信息举报专区</a><a target="_blank" rel="noopener noreferrer" href="/jubao">儿童色情信息举报专区</a><span>违法和不良信息举报:010-82716601</span></div><div class="ZhihuIntegrity"><div><img src="https://static.zhihu.com/static/revved/img/index/chengxing_logo@2x.65dc76e8.png" alt="诚信网站示范企业"/><a href="https://credit.szfw.org/CX20170607038331320388.html">诚信网站示范企业</a></div></div></footer></div></main></div></div><div id="data" style="display:none" data-state="{"common":{"ask":{}},"privacy":{"showPrivacy":false},"loading":{"global":{"count":0},"local":{"env/getExperiments/":false}},"entities":{"users":{},"questions":{},"answers":{},"articles":{},"columns":{},"topics":{},"roundtables":{},"favlists":{},"comments":{},"notifications":{},"ebooks":{},"activities":{},"feeds":{},"pins":{},"promotions":{},"drafts":{}},"currentUser":"","account":{"lockLevel":{},"unlockTicketStatus":false,"unlockTicket":null,"challenge":[],"errorStatus":false,"message":"","isFetching":false,"accountInfo":{},"urlToken":{"loading":false}},"settings":{"socialBind":null,"inboxMsg":null,"notification":{},"email":{},"privacyFlag":null,"blockedUsers":{"isFetching":false,"paging":{"pageNo":1,"pageSize":6},"data":[]},"blockedFollowees":{"isFetching":false,"paging":{"pageNo":1,"pageSize":6},"data":[]},"ignoredTopics":{"isFetching":false,"paging":{"pageNo":1,"pageSize":6},"data":[]},"restrictedTopics":null,"laboratory":{}},"notification":{},"people":{"profileStatus":{},"activitiesByUser":{},"answersByUser":{},"answersSortByVotesByUser":{},"answersIncludedByUser":{},"votedAnswersByUser":{},"thankedAnswersByUser":{},"voteAnswersByUser":{},"thankAnswersByUser":{},"topicAnswersByUser":{},"articlesByUser":{},"articlesSortByVotesByUser":{},"articlesIncludedByUser":{},"pinsByUser":{},"questionsByUser":{},"commercialQuestionsByUser":{},"favlistsByUser":{},"followingByUser":{},"followersByUser":{},"mutualsByUser":{},"followingColumnsByUser":{},"followingQuestionsByUser":{},"followingFavlistsByUser":{},"followingTopicsByUser":{},"publicationsByUser":{},"columnsByUser":{},"allFavlistsByUser":{},"brands":null},"env":{"ab":{"config":{"experiments":[{"expId":"launch-ad_rtl_http-2","expPrefix":"ad_rtl_http","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-gw_adr_mini-2","expPrefix":"gw_adr_mini","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-gw_adr_wbtp-2","expPrefix":"gw_adr_wbtp","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-gw_anr_wxbk-2","expPrefix":"gw_anr_wxbk","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-gw_ios_mini-2","expPrefix":"gw_ios_mini","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-gw_ios_wxb-2","expPrefix":"gw_ios_wxb","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-gw_unif-4","expPrefix":"gw_unif","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-gw_wbtp-2","expPrefix":"gw_wbtp","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-mp_hb_si-3","expPrefix":"mp_hb_si","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-mp_ios_webp-2","expPrefix":"mp_ios_webp","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-mp_video_feed-2","expPrefix":"mp_video_feed","isDynamicallyUpdated":false,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-vd_adrupload_cdn-2","expPrefix":"vd_adrupload_cdn","isDynamicallyUpdated":false,"isRuntime":false,"includeTriggerInfo":false},{"expId":"launch-vd_upload_cdn-2","expPrefix":"vd_upload_cdn","isDynamicallyUpdated":false,"isRuntime":false,"includeTriggerInfo":false},{"expId":"top_dtmt-10","expPrefix":"top_dtmt","isDynamicallyUpdated":true,"isRuntime":false,"includeTriggerInfo":false}],"params":[{"id":"top_yhgc","type":"String","value":"0","chainId":"_all_"},{"id":"ios_ad_skip_pos","type":"String","value":"up"},{"id":"top_tag_isolation","type":"String","value":"0","chainId":"_all_"},{"id":"ios_video_agent_4_22","type":"String","value":"false"},{"id":"top_lowup","type":"String","value":"1","chainId":"_all_"},{"id":"top_tr","type":"String","value":"0","chainId":"_all_"},{"id":"top_video_rew","type":"String","value":"0","chainId":"_all_"},{"id":"tp_sft","type":"String","value":"a","chainId":"_all_"},{"id":"adr_comment","type":"String","value":"false"},{"id":"adr_task_statistics","type":"String","value":"false"},{"id":"top_alt","type":"String","value":"0","chainId":"_all_"},{"id":"ios_ad_cta","type":"String","value":"0"},{"id":"adr_edit_question","type":"String","value":"0"},{"id":"adr_real_time_launch_http","type":"String","value":"http_off"},{"id":"ios_ps","type":"String","value":"0"},{"id":"top_billread","type":"String","value":"1","chainId":"_all_"},{"id":"top_nad","type":"String","value":"1","chainId":"_all_"},{"id":"top_newfollow","type":"String","value":"0","chainId":"_all_"},{"id":"adr_unif","type":"String","value":"on"},{"id":"top_an","type":"String","value":"0","chainId":"_all_"},{"id":"ios_pdf","type":"String","value":"n"},{"id":"adr_android_video_continuous","type":"String","value":"0"},{"id":"adr_sqtc","type":"String","value":"1"},{"id":"top_billab","type":"String","value":"0","chainId":"_all_"},{"id":"top_feedre_cpt","type":"String","value":"101","chainId":"_all_"},{"id":"adr_cta","type":"String","value":"0"},{"id":"adr_topsearch","type":"String","value":"2"},{"id":"adr_mini","type":"String","value":"1"},{"id":"ios_qtoc","type":"String","value":"0"},{"id":"top_billupdate1","type":"String","value":"0","chainId":"_all_"},{"id":"top_feedre","type":"String","value":"1","chainId":"_all_"},{"id":"top_video_fix_position","type":"String","value":"0","chainId":"_all_"},{"id":"adr_book_is_card","type":"String","value":"0"},{"id":"adr_member_switch","type":"String","value":"0"},{"id":"ios_psn","type":"String","value":"n"},{"id":"top_followtop","type":"String","value":"0","chainId":"_all_"},{"id":"top_hqt","type":"String","value":"0","chainId":"_all_"},{"id":"top_nuc","type":"String","value":"0","chainId":"_all_"},{"id":"top_tagore","type":"String","value":"1","chainId":"_all_"},{"id":"adr_perm","type":"String","value":"0"},{"id":"ios_ge4","type":"String","value":"3"},{"id":"adr_profile_label","type":"String","value":"1"},{"id":"ios_answer_preload","type":"String","value":"0"},{"id":"ios_magitab","type":"String","value":"0"},{"id":"ios_video_feed","type":"String","value":"1"},{"id":"web_logoc","type":"String","value":"blue","chainId":"_all_"},{"id":"adr_editor_version","type":"String","value":"V2"},{"id":"adr_invite","type":"String","value":"false"},{"id":"ios_adr_vid_vol","type":"String","value":"0"},{"id":"top_login_card","type":"String","value":"1","chainId":"_all_"},{"id":"adr_anp","type":"String","value":"android_answer_pager_off"},{"id":"adr_traffic_leak","type":"String","value":"false"},{"id":"top_ntr","type":"String","value":"1","chainId":"_all_"},{"id":"top_root_few_topic","type":"String","value":"0","chainId":"_all_"},{"id":"top_sj","type":"String","value":"2","chainId":"_all_"},{"id":"ios_book_is_card","type":"String","value":"0"},{"id":"top_gr_topic_reweight","type":"String","value":"0","chainId":"_all_"},{"id":"ios_wbtp","type":"String","value":"1"},{"id":"top_nmt","type":"String","value":"0","chainId":"_all_"},{"id":"top_root_mg","type":"String","value":"1","chainId":"_all_"},{"id":"adr_ps","type":"String","value":"0"},{"id":"ios_profile_sig","type":"String","value":"true"},{"id":"top_yc","type":"String","value":"0","chainId":"_all_"},{"id":"adr_prt","type":"String","value":"false"},{"id":"pin_efs","type":"String","value":"orig","chainId":"_all_"},{"id":"adr_wxbk","type":"String","value":"1"},{"id":"top_nid","type":"String","value":"0","chainId":"_all_"},{"id":"ios_profile_badge","type":"String","value":"false"},{"id":"top_root_web","type":"String","value":"0","chainId":"_all_"},{"id":"top_follow_reason","type":"String","value":"0","chainId":"_all_"},{"id":"top_root","type":"String","value":"0","chainId":"_all_"},{"id":"ios_comment","type":"String","value":"0"},{"id":"top_billpic","type":"String","value":"0","chainId":"_all_"},{"id":"top_gr_auto_model","type":"String","value":"0","chainId":"_all_"},{"id":"top_universalebook","type":"String","value":"1","chainId":"_all_"},{"id":"top_vdio_rew","type":"String","value":"0","chainId":"_all_"},{"id":"adr_video_topic_volume_control","type":"String","value":"0"},{"id":"adr_wbtp","type":"String","value":"1"},{"id":"ios_wxbk","type":"String","value":"1"},{"id":"ios_le_nav","type":"String","value":"0"},{"id":"ios_spic","type":"String","value":"0"},{"id":"ls_play_continuous_order","type":"String","value":"1","chainId":"_all_"},{"id":"top_feedre_rtt","type":"String","value":"41","chainId":"_all_"},{"id":"ios_asp","type":"String","value":"off"},{"id":"ios_x_z_c0","type":"String","value":"1"},{"id":"top_30","type":"String","value":"0","chainId":"_all_"},{"id":"ios_km_center","type":"String","value":"0"},{"id":"ios_real_time_launch_is_http","type":"String","value":"1"},{"id":"top_feedre_itemcf","type":"String","value":"31","chainId":"_all_"},{"id":"top_mlt_model","type":"String","value":"0","chainId":"_all_"},{"id":"adr_spic","type":"String","value":"0"},{"id":"adr_traffic_monitor","type":"String","value":"false"},{"id":"ios_hybrid_editor_v3","type":"String","value":"0"},{"id":"ios_notif_new_invite","type":"String","value":"off"},{"id":"adr_guest_login","type":"String","value":"0"},{"id":"adr_ljb","type":"String","value":"launch_jump_button_up"},{"id":"ios_real_time_launch_http","type":"String","value":"http_off"},{"id":"ios_webp","type":"String","value":"1"},{"id":"top_ebook","type":"String","value":"0","chainId":"_all_"},{"id":"adr_use_cashier","type":"String","value":"new"},{"id":"ios_more_editcard","type":"String","value":"false"},{"id":"ios_q_bar","type":"String","value":"NO"},{"id":"ios_video_continuous","type":"String","value":"0"},{"id":"top_recall","type":"String","value":"1","chainId":"_all_"},{"id":"adr_anr_watch","type":"String","value":"false"},{"id":"ios_pay_view","type":"String","value":"new"},{"id":"ios_article_new_comment","type":"String","value":"0"},{"id":"top_billvideo","type":"String","value":"0","chainId":"_all_"},{"id":"top_is_gr","type":"String","value":"0","chainId":"_all_"},{"id":"top_nszt","type":"String","value":"0","chainId":"_all_"},{"id":"adr_medal","type":"String","value":"0"},{"id":"adr_q_bar","type":"String","value":"NO"},{"id":"ios_1752","type":"String","value":"0"},{"id":"ios_hybrid_intercepting","type":"String","value":"1"},{"id":"ios_next_ans","type":"String","value":"N"},{"id":"se_tf","type":"String","value":"1","chainId":"_all_"},{"id":"top_sjre","type":"String","value":"0","chainId":"_all_"},{"id":"adr_grow_guide_login_4","type":"String","value":"3"},{"id":"adr_profile_medal","type":"String","value":"0"},{"id":"ios_wxfb","type":"String","value":"1"},{"id":"top_billupdate","type":"String","value":"0","chainId":"_all_"},{"id":"top_multi_model","type":"String","value":"0","chainId":"_all_"},{"id":"top_tmt","type":"String","value":"0","chainId":"_all_"},{"id":"adr_more_hyb_card","type":"String","value":"0"},{"id":"adr_next_answer_btn","type":"String","value":"0"},{"id":"ios_mini","type":"String","value":"1"},{"id":"ios_video_upload_cdn","type":"String","value":"1"},{"id":"top_bill","type":"String","value":"0","chainId":"_all_"},{"id":"top_dtmt","type":"String","value":"2","chainId":"_all_"},{"id":"top_nucc","type":"String","value":"0","chainId":"_all_"},{"id":"top_tffrt","type":"String","value":"0","chainId":"_all_"},{"id":"adr_video_upload_cdn","type":"String","value":"1"},{"id":"ios_7324","type":"String","value":"0"},{"id":"web_ask_flow","type":"String","value":"default","chainId":"_all_"},{"id":"pin_ef","type":"String","value":"orig","chainId":"_all_"},{"id":"top_topic_feedre","type":"String","value":"21","chainId":"_all_"},{"id":"adr_wxfb","type":"String","value":"1"},{"id":"ios_apm","type":"String","value":"0"},{"id":"top_gif","type":"String","value":"0","chainId":"_all_"},{"id":"top_gr_model","type":"String","value":"0","chainId":"_all_"},{"id":"adr_pdf","type":"String","value":"n"},{"id":"adr_traffic_threshold","type":"String","value":"314572800"}],"chains":[{"chainId":"_all_"}]},"triggers":{}},"experiment":{"ge3":"ge3_10","ge2":"ge2_1","searchAdvertPosition":"1","growthSearch":"s2","nwebQAGrowth":"experiment","qawebRelatedReadingsContentControl":"close","liveStore":"ls_a1_b1_c1_f2","nwebSearch":"nweb_search_heifetz","searchHybridTabs":"pin-3#album-7","newSignBg":"new","rt":"y","isOffice":"false","newLiveFeedMediacard":"new","newMobileAppHeader":"true","androidPassThroughPush":"all","np":"1","hybridZhmoreVideo":"yes","nwebGrowthPeople":"default","nwebSearchSuggest":"default","qrcodeLogin":"qrcode","isShowUnicomFreeEntry":"unicom_free_entry_off","androidSearchTabStyle":"search_tab_style_b","newMobileColumnAppheader":"new_header","androidDbRecommendAction":"open","searchTab":"collapse","zcmLighting":"zcm","androidDbFeedHashTagStyle":"button","appStoreRateDialog":"close","mobileFeedGuide":"block","default":"None","isNewNotiPanel":"no","adR":"a","uRe":"0","androidProfilePanel":"panel_b"},"experimentOrigin":{"ge3":"ge3_10","ge2":"ge2_1","search_advert_position":"1","growth_search":"s2","nwebQAGrowth":"experiment","qaweb_related_readings_content_control":"close","live_store":"ls_a1_b1_c1_f2","nweb_search":"nweb_search_heifetz","search_hybrid_tabs":"pin-3#album-7","new_sign_bg":"new","rt":"y","is_office":"false","new_live_feed_mediacard":"new","new_mobile_app_header":"true","android_pass_through_push":"all","np":"1","hybrid_zhmore_video":"yes","nweb_growth_people":"default","nweb_search_suggest":"default","qrcode_login":"qrcode","is_show_unicom_free_entry":"unicom_free_entry_off","android_search_tab_style":"search_tab_style_b","new_mobile_column_appheader":"new_header","android_db_recommend_action":"open","search_tab":"collapse","zcm-lighting":"zcm","android_db_feed_hash_tag_style":"button","app_store_rate_dialog":"close","mobile_feed_guide":"block","default":"None","is_new_noti_panel":"no","ad_r":"a","u_re":"0","android_profile_panel":"panel_b"},"userAgent":{"Edge":false,"Wechat":false,"Weibo":false,"QQ":false,"Mobile":false,"Android":false,"iOS":false,"isAppleDevice":true,"Zhihu":false,"ZhihuHybrid":false,"isBot":false,"Tablet":false,"UC":false,"Sogou":false,"Qihoo":false,"Baidu":false,"isWebView":false,"origin":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36"},"trafficSource":"production","edition":{"baidu":false,"sogou":false,"baiduBeijing":false,"yidianzixun":false},"theme":"light","referer":"","conf":{},"ipInfo":{},"logged":false},"me":{"accountInfoLoadStatus":{},"organizationProfileStatus":{},"columnContributions":[]},"comments":{"pagination":{},"collapsed":{},"reverse":{},"reviewing":{},"conversation":{},"parent":{}},"pushNotifications":{"default":{"isFetching":false,"isDrained":false,"ids":[]},"follow":{"isFetching":false,"isDrained":false,"ids":[]},"vote_thank":{"isFetching":false,"isDrained":false,"ids":[]},"currentTab":"default","notificationsCount":{"default":0,"follow":0,"vote_thank":0}},"messages":{"data":{},"currentTab":"common","messageCount":0},"register":{"registerValidateSucceeded":null,"registerValidateErrors":{},"registerConfirmError":null,"sendDigitsError":null,"registerConfirmSucceeded":null},"login":{"loginUnregisteredError":false,"loginBindWechatError":false,"loginConfirmError":null,"sendDigitsError":null,"validateDigitsError":false,"loginConfirmSucceeded":null,"qrcodeLoginToken":"","qrcodeLoginScanStatus":0,"qrcodeLoginError":null,"qrcodeLoginReturnNewToken":false},"active":{"sendDigitsError":null,"activeConfirmSucceeded":null,"activeConfirmError":null},"switches":{},"coupon":{"isRedeemingCoupon":false},"question":{"followers":{},"concernedFollowers":{},"answers":{},"hiddenAnswers":{},"createdAnswers":{},"collapsedAnswers":{},"notificationAnswers":{},"invitationCandidates":{},"inviters":{},"invitees":{},"similarQuestions":{},"relatedCommodities":{},"recommendReadings":{},"bio":{},"brand":{},"permission":{},"advancedStyle":{},"commonAnswerCount":0,"hiddenAnswerCount":0,"meta":{},"autoInvitation":{},"simpleConcernedFollowers":{}},"shareTexts":{},"answers":{"voters":{},"copyrightApplicants":{},"favlists":{},"newAnswer":{},"concernedUpvoters":{},"simpleConcernedUpvoters":{}},"banner":{},"topic":{"bios":{},"hot":{},"newest":{},"top":{},"unanswered":{},"questions":{},"followers":{},"parent":{},"children":{},"bestAnswerers":{},"index":{},"intro":{},"meta":{},"schema":{}},"captcha":{"captchaNeeded":false,"captchaValidated":false,"captchaBase64String":null,"captchaValidationMessage":null,"loginCaptchaExpires":false},"sms":{"supportedCountries":[]},"explore":{"recommendations":{}},"articles":{"voters":{}},"favlists":{"relations":{}},"pins":{"voters":{}},"topstory":{"topstorys":{"isFetching":false,"isDrained":false,"afterId":0,"items":[],"next":null},"sidebar":null,"announcement":{},"hotList":[],"guestFeeds":{"isFetching":false,"isDrained":false,"afterId":0,"items":[],"next":null}},"upload":{},"video":{"data":{}},"guide":{"guide":{"isFetching":false,"isShowGuide":false}},"reward":{"answer":{},"article":{},"question":{}},"search":{"recommendSearch":[],"topSearch":{},"attachedInfo":{},"nextOffset":{},"generalByQuery":{},"generalByQueryInADay":{},"generalByQueryInAWeek":{},"generalByQueryInThreeMonths":{},"peopleByQuery":{},"topicByQuery":{},"columnByQuery":{},"liveByQuery":{},"albumByQuery":{},"eBookByQuery":{}},"creator":{"tools":{"question":{"invitationCount":{"questionFolloweeCount":0,"questionTotalCount":0},"goodatTopics":[]},"customPromotion":{"itemLists":{}}},"explore":{"academy":{"tabs":[],"article":{}}},"rights":[],"rightsStatus":{}},"publicEditPermission":{}}" data-config="{"apiAddress":"/api/v4/","deployEnv":"production"}" data-useragent="{"os":{"name":"Mac OS","version":"10.11.4"},"browser":{"name":"Chrome","version":"53.0.2785.116","major":"53"}}"></div><script src="https://static.zhihu.com/heifetz/vendor.caf889932b6061dcc35e.js"></script><script src="https://static.zhihu.com/heifetz/main.raven.d45641973a98a902cea1.js" defer=""></script><script src="https://static.zhihu.com/heifetz/main.app.cf660aebca0ff7adefa1.js"></script><script></script></body></html>
```
当然也可以通过 cookies 参数来设置,不过这样就需要构造 RequestsCookieJar 对象,而且需要分割一下 Cookies ,相对繁琐,不过效果是相同的,实例如下:
```text
import requests
cookies = 'q_c1=31653b264a074fc9a57816d1ea93ed8b|1474273938000|1474273938000; d_c0="AGDAs254kAqPTr6NW1U3XTLFzKhMPQ6H_nc=|1474273938"; __utmv=51854390.100-1|2=registration_date=20130902=1^3=entry_date=20130902=1;a_t="2.0AACAfbwdAAAXAAAAso0QWAAAgH28HQAAAGDAs254kAoXAAAAYQJVTQ4FCVgA360us8BAklzLYNEHUd6kmHtRQX5a6hiZxKCynnycerLQ3gIkoJLOCQ==";z_c0=Mi4wQUFDQWZid2RBQUFBWU1DemJuaVFDaGNBQUFCaEFsVk5EZ1VKV0FEZnJTNnp3RUNTWE10ZzBRZFIzcVNZZTFGQmZn|1474887858|64b4d4234a21de774c42c837fe0b672fdb5763b0'
jar = requests.cookies.RequestsCookieJar()
headers = {
'Host': 'www.zhihu.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'
}
for cookie in cookies.split(';'):
key, value = cookie.split('=', 1)
jar.set(key, value)
r = requests.get('http://www.zhihu.com', cookies=jar, headers=headers)
print(r.text)
```
首先新建了一个 RequestCookieJar 对象,然后将复制下来的 Cookies 利用 split\(\) 方法分割,利用 set\(\) 方法设置好每一个 Cookie 的 key 和 value,然后通过调用 Requests 的 get\(\) 方法并传递给 cookies 参数即可,当然由于知乎本身的限制, headers 参数也不能少,只不过不需要在原来的 headers 参数里面设置 Cookie 字段了
## 3. 会话维持 {#3-会话维持}
测试网址:[http://httpbin.org/cookies/set/number/123456789](http://httpbin.org/cookies/set/number/123456789)
解决这个问题的主要方法就是维持同一个会话,也就是相当于打开一个新的浏览器选项卡而不是新开一个浏览器。但是我又不想每次设置 Cookies,那该怎么办?这时候就有了新的利器 Session对象。
利用它,我们可以方便地维护一个会话,而且不用担心 Cookies 的问题,它会帮我们自动处理好
实例:
```text
import requests
requests.get("http://httpbin.org/cookies/set/number/123456789")
r = requests.get("http://httpbin.org/cookies")
print(r.text)
```
运行结果:
```text
{
"cookies": {
}
}
```
不能成功获取到设置的 Cookies
使用session测试
```text
import requests
s = requests.Session()
s.get("http://httpbin.org/cookies/set/number/123456789")
r = s.get("http://httpbin.org/cookies")
print(r.text)
```
运行结果:
```text
{
"cookies": {
"number": "123456789"
}
}
```
利用 Session 我们可以做到模拟同一个会话,而且不用担心 Cookies 的问题,通常用于模拟登录成功之后再进行下一步的操作
## 4. SSL证书验证 {#4-ssl证书验证}
测试网址:[https://www.12306.cn](https://www.12306.cn)
Requests 提供了证书验证的功能,当发送 HTTP 请求的时候,它会检查 SSL 证书,我们可以使用 verify 这个参数来控制是否检查此证书,其实如果不加的话默认是 True,会自动验证。
测试:
```text
import requests
response = requests.get("https://www.12306.cn")
print(response.status_code)
```
运行结果:
```text
requests.exceptions.SSLError: HTTPSConnectionPool(host='www.12306.cn', port=443): Max retries exceeded with url: / (Caused by SSLError(CertificateError("hostname 'www.12306.cn' doesn't match either of 'webssl.chinanetcenter.com', 'i.l.inmobicdn.net', '*.fn-mart.com', 'www.1zhe.com', '*.pinganfang.com', '*.anhouse.com', 'dl.jphbpk.gxpan.cn', 'dl.givingtales.gxpan.cn', 'dl.toyblast.gxpan.cn', 'dl.sds.gxpan.cn', 'download.ctrip.com', 'mh.tiancity.com', 'app.4399.cn', 'i.4399.cn', 'm.4399.cn', 'a.4399.cn', 'cdn.hxjyios.iwan4399.com', 'ios.hxjy.iwan4399.com', 'gjzx.gjzq.com.cn', 'f.3000test.com', 'tj.img4399.com', '*.zhe800.com', '*.qiyipic.com', '*.vxinyou.com', '*.gdjh.vxinyou.com', '*.3000.com', 'pay.game2.cn', 'static1.j.cn', 'static2.j.cn', 'static3.j.cn', 'static4.j.cn', 'video1.j.cn', 'video2.j.cn', 'video3.j.cn', 'online.j.cn', 'playback.live.j.cn', 'audio1.guang.j.cn', 'audio2.guang.j.cn', 'audio3.guang.j.cn', 'img1.guang.j.cn', 'img2.guang.j.cn', 'img3.guang.j.cn', 'img4.guang.j.cn', 'img5.guang.j.cn', 'img6.guang.j.cn', '*.4399youpai.com', 'w.tancdn.com', '*.3000api.com', 'static11.j.cn', '*.kuyinyun.com', '*.kuyin123.com', '*.diyring.cc', '3000test.com', '*.3000test.com', 'www.3387.com', 'bbs.4399.cn', '*.cankaoxiaoxi.com', '*.service.kugou.com', 'test.macauslot.com', 'testm.macauslot.com', 'testtran.macauslot.com', 'xiuxiu.huodong.meitu.com', '*.meitu.com', '*.meitudata.com', '*.wheetalk.com', '*.shanliaoapp.com', 'xiuxiu.web.meitu.com', 'api.account.meitu.com', 'open.web.meitu.com', 'id.api.meitu.com', 'api.makeup.meitu.com', 'im.live.meipai.com', '*.meipai.com', 'm.macauslot.com', 'www.macauslot.com', 'web.macauslot.com', 'translation.macauslot.com', 'img1.homekoocdn.com', 'cdn.homekoocdn.com', 'cdn1.homekoocdn.com', 'cdn2.homekoocdn.com', 'cdn3.homekoocdn.com', 'cdn4.homekoocdn.com', 'img.homekoocdn.com', 'img2.homekoocdn.com', 'img3.homekoocdn.com', 'img4.homekoocdn.com', '*.macauslot.com', '*.samsungapps.com', 'auto.tancdn.com', '*.winbo.top', 'static.bst.meitu.com', 'api.xiuxiu.meitu.com', 'api.photo.meituyun.com', 'h5.selfiecity.meitu.com', 'api.selfiecity.meitu.com', 'h5.beautymaster.meiyan.com', 'api.beautymaster.meiyan.com', 'www.yawenb.com', 'm.yawenb.com', 'www.biqugg.com', 'www.dawenxue.net', 'cpg.meitubase.com', 'www.qushuba.com', 'www.ranwena.com', 'www.u8xsw.com', '*.4399sy.com', 'ms.awqsaged.cn', 'fanxing2.kugou.com', 'fanxing.kugou.com', 'sso.56.com', 'upload.qf.56.com', 'sso.qianfan.tv', 'cdn.danmu.56.com', 'www-ppd.hermes.cn', 'www-uat.hermes.cn', 'www-ts2.hermes.cn', 'www-tst.hermes.cn', '*.syyx.com', 'img.wgeqr.cn', 'img.wgewa.cn', 'img.09mk.cn', 'img.85nh.cn', '*.zhuoquapp.com', 'img.dtmpekda8.cn', 'img.etmpekda6.cn', '*.5054399.com', '*.aiwan4399.com', 'user.beevideo.bestv.com.cn', '*.3839.com', '*.actdelivery.net', '*.4399.cn'",),))
```
提示一个错误,叫做 SSLError,证书验证错误。所以如果我们请求一个 HTTPS 站点,但是证书验证错误的页面时,就会报这样的错误
如何避免这个错误,只需把 verify 这个参数设置为 False 即可。
```text
import requests
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)
```
运行结果:
```text
E:\Python36\lib\site-packages\urllib3\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
200
```
不过发现报了一个警告,它提示建议让我们给它指定证书。
可以通过设置忽略警告的方式来屏蔽这个警告:
```text
import requests
import urllib3
urllib3.disable_warnings()
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)
```
运行结果:
```text
200
```
或者通过捕获警告到日志的方式忽略警告:
```text
import requests
import logging
logging.captureWarnings(True)
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)
```
可以指定一个本地证书用作客户端证书,可以是单个文件(包含密钥和证书)或一个包含两个文件路径的元组
```text
import requests
response = requests.get('https://www.12306.cn',verify="E:/SRCA.crt")
print(response.status_code)
```
## 5. 代理设置 {#5-代理设置}
设置代理,在 Requests 中需要用到 proxies 这个参数
```text
import requests
# 代理池
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
r = requests.get('https://www.taobao.com',proxies=proxies)
print(r.status_code)
```
若代理需要使用 HTTP Basic Auth,可以使用类似[http://user:password@host:port](http://user:password@host:port/)这样的语法来设置代理
实例:
```text
import requests
proxies = {
'https': 'http://user:password@10.10.1.10:3128/',
}
requests.get('https://www.taobao.com', proxies=proxies)
```
除了基本的 HTTP 代理,Requests 还支持 SOCKS 协议的代理。
需要安装 Socks 这个库,命令如下:
```text
pip3 install "requests[socks]"
```
然后就可以使用 SOCKS 协议代理了
```text
socks5://user:password@host:port
```
实例:
```text
import requests
proxies = {
'http': 'socks5://user:password@host:port',
'https': 'socks5://user:password@host:port'
}
requests.get('https://www.taobao.com', proxies=proxies)
```
## 6. 超时设置 {#6-超时设置}
设置超时时间需要用到 timeout 参数。这个时间的计算是发出 Request 到服务器返回 Response 的时间
```text
import requests
r = requests.get('https://www.taobao.com', timeout=1)
print(r.status_code)
```
通过这样的方式,我们可以将超时时间设置为 1 秒,如果 1 秒内没有响应,那就抛出异常。
实际上请求分为两个阶段,即 connect(连接)和 read(读取)。
上面的设置 timeout 值将会用作 connect 和 read 二者的 timeout 总和。
如果要分别指定,就可以传入一个元组:
```text
r = requests.get('https://www.taobao.com', timeout=(5, 11))
```
如果想永久等待,那么我们可以直接将 timeout 设置为 None,或者不设置直接留空,因为默认是 None。这样的话,如果服务器还在运行,但是响应特别慢,那就慢慢等吧,它永远不会返回超时错误的。
```text
r = requests.get('https://www.taobao.com', timeout=None)
或者
r = requests.get('https://www.taobao.com')
```
## 7. 身份认证 {#7-身份认证}
![](https://box.kancloud.cn/704a30d1c927252998e78b3ee839d1df_1530x1238.png)有可能遇到这样的页面认证,可以使用Requests字典的身份认证功能
```text
import requests
from requests.auth import HTTPBasicAuth
r = requests.get('http://localhost:5000', auth=HTTPBasicAuth('username', 'password'))
print(r.status_code)
```
更简便的认证,可以直接传一个元组,它会默认使用 HTTPBasicAuth 这个类来认证
```text
import requests
r = requests.get('http://localhost:5000', auth=('username', 'password'))
print(r.status_code)
```
Requests 还提供了其他的认证方式,如 OAuth 认证,不过需要安装 oauth 包
```text
pip install requests_oauthlib
```
使用OAuth1方法认证
```text
import requests
from requests_oauthlib import OAuth1
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')
requests.get(url,auth=auth)
```
requests\_oauthlib官方文档:[https://requests-oauthlib.readthedocs.org/](https://requests-oauthlib.readthedocs.org/)
## 8. Prepared Request {#8-prepared-request}
实例:
```text
from requests import Request,Session
url = 'http://httpbin.org/post'
data = {
'name':'angle',
}
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'
}
s = Session()
req = Request('POST',url,data=data,headers=headers)
prepped = s.prepare_request(req)
r = s.send(prepped)
print(r.text)
```
引入 Request,然后用 url、data、headers 参数构造了一个 Request 对象,需要再调用 Session 的 prepare\_request\(\) 方法将其转换为一个 Prepared Request 对象,然后调用 send\(\) 方法发送即可
运行结果:
```text
{
"args": {},
"data": "",
"files": {},
"form": {
"name": "angle"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "10",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36"
},
"json": null,
"origin": "220.197.208.229",
"url": "http://httpbin.org/post"
}
```
有了 Request 这个对象,就可以将一个个请求当做一个独立的对象来看待,这样在进行队列调度的时候会非常方便
## 9.相关链接
官方文档:[http://docs.python-requests.org/](http://docs.python-requests.org/)
- 介绍
- 1.开发环境配置
- 1.1 python3的安装
- 1.1.1 windows下的安装
- 1.1.2 Linux下的安装
- 1.1.3 Mac下的安装
- 1.2 请求库的安装
- 1.2.1 requests的安装
- 1.2.2 selenium的安装
- 1.2.3 ChromeDriver的安装
- 1.2.4 GeckoDriver 的安装
- 1.2.5 PhantomJS的安装
- 1.2.6 aiohttp的安装
- 1.3 解析库的安装
- 1.3.1 lxml的安装
- 1.3.2 Beautiful Soup的安装
- 1.3.3 pyquery的安装
- 1.3.4 tesserocr的安装
- 1.4 数据库的安装
- 1.4.1 MySQL的安装
- 1.4.2 MongoDB的安装
- 1.4.3 Redis的安装
- 1.5 存储库的安装
- 1.5.1 PyMySQL的安装
- 1.5.2 PyMongo的安装
- 1.5.3 redis-py的安装
- 1.5.4 RedisDump的安装
- 1.6 Web库的安装
- 1.6.1 Flask的安装
- 1.6.2 Tornado的安装
- 1.7 App爬取相关库的安装
- 1.7.1 Charles的安装
- 1.7.2 mitmproxy的安装
- 1.7.3 Appium的安装
- 1.8 爬虫框架的安装
- 1.8.1 pyspider的安装
- 1.8.2 Scrapy的安装
- 1.8.3 Scrapy-Splash的安装
- 1.8.4 ScrapyRedis的安装
- 1.9 布署相关库的安装
- 1.9.1 Docker的安装
- 1.9.2 Scrapyd的安装
- 1.9.3 ScrapydClient的安装
- 1.9.4 ScrapydAPI的安装
- 1.9.5 Scrapyrt的安装
- 1.9.6-Gerapy的安装
- 2.爬虫基础
- 2.1 HTTP 基本原理
- 2.1.1 URI和URL
- 2.1.2 超文本
- 2.1.3 HTTP和HTTPS
- 2.1.4 HTTP请求过程
- 2.1.5 请求
- 2.1.6 响应
- 2.2 网页基础
- 2.2.1网页的组成
- 2.2.2 网页的结构
- 2.2.3 节点树及节点间的关系
- 2.2.4 选择器
- 2.3 爬虫的基本原理
- 2.3.1 爬虫概述
- 2.3.2 能抓怎样的数据
- 2.3.3 javascript渲染的页面
- 2.4 会话和Cookies
- 2.4.1 静态网页和动态网页
- 2.4.2 无状态HTTP
- 2.4.3 常见误区
- 2.5 代理的基本原理
- 2.5.1 基本原理
- 2.5.2 代理的作用
- 2.5.3 爬虫代理
- 2.5.4 代理分类
- 2.5.5 常见代理设置
- 3.基本库使用
- 3.1 使用urllib
- 3.1.1 发送请求
- 3.1.2 处理异常
- 3.1.3 解析链接
- 3.1.4 分析Robots协议
- 3.2 使用requests
- 3.2.1 基本用法
- 3.2.2 高级用法
- 3.3 正则表达式
- 3.4 抓取猫眼电影排行
- 4.解析库的使用
- 4.1 使用xpath
- 4.2 使用Beautiful Soup
- 4.3 使用pyquery
- 5.数据存储
- 5.1 文件存储
- 5.1.1 TXT 文件存储
- 5.1.2 JSON文件存储
- 5.1.3 CSV文件存储
- 5.2 关系型数据库存储
- 5.2.1 MySQL的存储
- 5.3 非关系数据库存储
- 5.3.1 MongoDB存储
- 5.3.2 Redis存储
- 6.Ajax数据爬取
- 6.1 什么是Ajax
- 6.2 Ajax分析方法
- 6.3 Ajax结果提取
- 6.4 分析Ajax爬取今日头条街拍美图
- 7.动态渲染页面爬取
- 7.1 Selenium的使用
- 7.2 Splash的使用
- 7.3 Splash负载均衡配置
- 7.4 使用selenium爬取淘宝商品
- 8.验证码的识别
- 8.1 图形验证码的识别
- 8.2 极验滑动验证码的识别
- 8.3 点触验证码的识别
- 8.4微博宫格验证码的识别
- 9.代理的使用
- 9.1 代理的设置
- 9.2 代理池的维护
- 9.3 付费代理的使用
- 9.4 ADSL拨号代理
- 9.5 使用代理爬取微信公总号文章
- 10.模拟登录
- 10.1 模拟登陆并爬去GitHub
- 10.2 Cookies池的搭建
- 11.App的爬取
- 11.1 Charles的使用
- 11.2 mitmproxy的使用
- 11.3 mitmdump“得到”App电子书信息
- 11.4 Appium的基本使用
- 11.5 Appnium爬取微信朋友圈
- 11.6 Appium+mitmdump爬取京东商品
- 12.pyspider框架的使用
- 12.1 pyspider框架介绍
- 12.2 pyspider的基本使用
- 12.3 pyspider用法详解
- 13.Scrapy框架的使用
- 13.1 scrapy框架介绍
- 13.2 入门
- 13.3 selector的用法
- 13.4 spider的用法
- 13.5 Downloader Middleware的用法
- 13.6 Spider Middleware的用法
- 13.7 Item Pipeline的用法
- 13.8 Scrapy对接Selenium
- 13.9 Scrapy对接Splash
- 13.10 Scrapy通用爬虫
- 13.11 Scrapyrt的使用
- 13.12 Scrapy对接Docker
- 13.13 Scrapy爬取新浪微博
- 14.分布式爬虫
- 14.1 分布式爬虫原理
- 14.2 Scrapy-Redis源码解析
- 14.3 Scrapy分布式实现
- 14.4 Bloom Filter的对接
- 15.分布式爬虫的部署
- 15.1 Scrapyd分布式部署
- 15.2 Scrapyd-Client的使用
- 15.3 Scrapyd对接Docker
- 15.4 Scrapyd批量部署
- 15.5 Gerapy分布式管理
- 微信公总号文章实战
- 源码
- other