前面讲了Python的urllib库的使用和方法,Python的网络数据采集Urllib库的基本使用,Python的urllib的高级用法。今天我们将学习如何在Python中使用Requests库。Requests库的安装使用pip安装。如果你已经安装了pip包(一个Python包管理工具,不知道能不能百度一下),或者集成环境,比如Python(x,y)或者anaconda,可以直接使用pip安装库进行Python。$pipinstallrequests安装完成后,我们看一下基本方法:#get请求方法>>>r=requests.get('https://api.github.com/user',auth=('user','pass'))#打印get请求的状态码>>>r.status_code200#查看请求的数据类型,可以看到是json格式,utf-8编码>>>r.headers['content-type']'application/json;charset=utf8'>>>r.encoding'utf-8'#打印请求内容>>>r.textu'{"type":"User"...'#输出json格式数据>>>r.json(){u'private_gists':419,u'total_private_repos':77,...}下面举个小栗子:#Smallexampleimportrequestsr=requests.get('http://www.baidu.com')printtype(r)printr.status_codeprintr.encodingprintr.textprintr.cookies'''请求百度的URL,然后打印出返回结果的类型、状态码、编码方式、Cookies等内容输出:'''200UTF-8http基本请求requests库提供了http的所有基本请求方法。例如:r=requests.post("http://httpbin.org/post")r=requests.put("http://httpbin.org/put")r=requests.delete("http://httpbin.org/delete")r=requests.head("http://httpbin.org/get")r=requests.options("http://httpbin.org/get")r=requests.get("http://httpbin.org/get")#如果要添加参数,可以使用params参数:importrequestspayload={'key1':'value1','key2':'value2'}r=requests.get("http://httpbin.org/get",params=payload)printr.url#Output:http://httpbin.org/get?key2=value2&key1=value1如果你想请求一个JSON文件,你可以使用json()方法解析,比如写一个名为a.json的JSON文件,内容如下:["foo","bar",{"foo":"bar"}]#使用如下程序请求并解析:importrequestsr=requests。get("a.json")printr.textprintr.json()'''结果如下,其中一种是直接输出内容,另一种是使用json()方法解析并感受差异:'''["foo","bar",{"foo":"bar"}][u'foo',u'bar',{u'foo':u'bar'}]如果你想得到原始的Socket响应,可以得到r.raw但是您需要在初始请求中设置stream=True。r=requests.get('https://github.com/timeline.json',stream=True)r.raw#outputr.raw.read(10)'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'这样就得到了网页原来的socket内容。如果要添加headers,可以传headers参数:importrequestspayload={'key1':'value1','key2':'value2'}headers={'content-type':'application/json'}r=requests.get("http://httpbin.org/get",params=payload,headers=headers)printr.url#可以通过headers参数添加请求头中的headers信息。基本POST请求对于一个POST请求,我们一般需要为它添加一些参数。那么最基本的参数传递方式就可以使用data参数了。importrequestspayload={'key1':'value1','key2':'value2'}r=requests.post("http://httpbin.org/post",data=payload)printr.text#运行结果如下:{"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip,deflate","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"http://httpbin.org","User-Agent":"python-requests/2.9.1"},"json":null,"url":"http://httpbin.org/post"},可以看到参数传递成功,然后服务器返回了我们传递的数据。有时候我们需要传递的信息不是表单形式,需要传递JSON格式的数据,那么可以使用json.dumps()方法将表单数据序列化。importjsonimportrequestsurl='http://httpbin.org/post'payload={'some':'data'}r=requests.post(url,data=json.dumps(payload))printr.text#运行结果:{"args":{},"data":"{\"some\":\"data\"}","files":{},"form":{},"headers":{"Accept":"*/*","Accept-Encoding":"gzip,deflate","Content-Length":"16","Host":"http://httpbin.org","User-Agent":"python-requests/2.9.1"},"json":{"some":"data"},"url":"http://httpbin.org/post"}通过上面的方法,我们可以POSTJSONformat如果要为数据上传一个文件,可以直接使用file参数:#新建一个test.txt文件,写HelloWorld!importrequestsurl='http://httpbin.org/post'files={'file':open('test.txt','rb')}r=requests.post(url,files=files)printr.text{"args":{},"data":"","files“:{"file":"HelloWorld!"},"form":{},"headers":{"Accept":"*/*","Accept-Encoding":"gzip,deflate","Content-Length":"156","Content-Type":"multipart/form-data;boundary=7d8eb5ff99a04c11bb3e862ce78d7000","Host":"http://httpbin.org","User-Agent":"python-requests/2.9.1"},"json":null,"url":"http://httpbin.org/post"}这样,我们就顺利完成了一个文件的上传。requests支持流式上传,这允许您发送大数据流或文件而无需先将它们读入内存。要使用流式上传,只需为您的请求主体提供一个类似文件的对象,非常方便:withopen('massive-body')asf:requests.post('http://some.url/streamed',data=f)Cookies如果响应包含cookies,我们可以使用cookies变量来获取它们:importrequestsurl='ExampleDomain'r=requests.get(url)printr.cookiesprintr.cookies['example_cookie_name']只是一个样本。您可以使用cookies变量来获取站点的cookies。另外,可以使用cookies变量向服务器发送cookies信息:importrequestsurl='http://httpbin.org/cookies'cookies=dict(cookies_are='working')r=requests.get(url,cookies=cookies)printr.text#Output:'{"cookies":{"cookies_are":"working"}}'超时配置可以使用timeout变量配置最大请求时间requests.get('更好的构建软件,一起',timeout=0.001)注意:超时只对连接过程有效,与响应体的下载无关。也就是说,这个时间只是限制了请求的时间。即使返回的响应包含很多内容,下载也需要一些时间。Session对象在上面的请求中,每一次请求其实都相当于发起了一个新的请求。也就是说相当于我们用不同的浏览器分别打开每个请求的效果。也就是说,它不引用会话,即使请求相同的URL。例如:importrequestsrequests.get('http://httpbin.org/cookies/set/sessioncookie/123456789')r=requests.get("http://httpbin.org/cookies")print(r.text)#结果是:{"cookies":{}}很明显,这个不在session中,获取不到cookies,那么在某些站点需要保持session持久化怎么办呢?就像用浏览器浏览淘宝一样,在不同的标签页之间跳转,其实就是在建立一个长期会话。解决方法如下:importrequests=requests.Session()s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')r=s.get("http://httpbin.org/cookies")print(r.text)#这里我们请求了两次,一次是设置cookies,一次是获取cookies{"cookies":{"sessioncookie":"123456789"}}发现cookies可以获取成功,这就是建立会话的作用。所以既然session是一个全局变量,我们肯定可以用它来进行全局配置。importrequestss=requests.Session()s.headers.update({'x-test':'true'})r=s.get('http://httpbin.org/headers',headers={'x-test2':'true'})printr.text'''headers变量是通过s.headers.update方法设置的。那么我们在请求中设置一个headers,那么会发生什么呢?很简单,两个变量都传过去了。运行结果:'''{"headers":{"Accept":"*/*","Accept-Encoding":"gzip,deflate","Host":"http://httpbin.org","User-Agent":"python-requests/2.9.1","X-Test":"true","X-Test2":"true"}}如果get方法传过来的header也是x-test呢?r=s.get('http://httpbin.org/headers',headers={'x-test':'true'})#会覆盖全局配置:{"headers":{"Accept":"*/*","Accept-Encoding":"gzip,deflate","Host":"http://httpbin.org","User-Agent":"python-requests/2.9.1","X-Test":"true"}}如果您不想在全局配置中使用变量怎么办?很简单,设置为None。r=s.get('http://httpbin.org/headers',headers={'x-test':None}){"headers":{"Accept":"*/*","Accept-Encoding":"gzip,deflate","Host":"http://httpbin.org","User-Agent":"python-requests/2.9.1"}}以上是session会话的基本用法。SSL证书验证现在在https开头的网站随处可见,Requests可以为HTTPS请求验证SSL证书,就像网页浏览器一样。查看某台主机的SSL证书,可以使用verify参数,因为前段时间12306证书没有失效,我们测试一下:importrequestsr=requests.get('https://kyfw.12306.cn/otn/',verify=True)printr.text#Result:requests.exceptions.SSLError:[SSL:CERTIFICATE_VERIFY_FAILED]证书验证失败(_ssl.c:590)尝试github:importrequestsr=requests.get('Buildsoftwarebetter,together',verify=True)printr.text嗯,正常请求,因为内容太多,就不贴输出了。如果我们想跳过刚才的12306证书验证,只需将verify设置为False即可:可以正常请求。verify默认为True,因此需要时需要手动设置此变量。代理如果您需要使用代理,您可以通过向任何请求方法提供代理参数来配置单独的请求。importrequestsproxies={"https":"http://41.118.132.69:4433"}r=requests.post("http://httpbin.org/post",proxies=proxies)printr.text#也可以通过环境变量HTTP_PROXY和HTTPS_PROXY配置代理exportHTTP_PROXY="http://10.10.1.10:3128"exportHTTPS_PROXY="http://10.10.1.10:1080"