-
Requests
2020-07-02 16:05:21安装 Requests 打开终端,使用pip安装 pip install requests 如果你没有安装 pip (啧啧),那就看下面的 点这个链接下载包 或者执行以下命令获取包 curl -OL https://github.com/requests/requests/tarball/master ...安装 Requests
打开终端,使用
pip
安装pip install requests
这可能会比较慢或者失败,如果失败可以尝试下面这个
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
如果你没有安装
pip
(啧啧),那就看下面的下载zip包
git地址获得源码之后可以解压到 python 包里,或者安装到你的
site-packages
然后回到终端,切换到该目录执行python setup.py install
Requests基本使用
发送请求
>>>import requests >>>r = requests.get('https://api.github.com/events') >>>r = requests.post('http://httpbin.org/post', data = {'key':'value'}) >>>r = requests.put('http://httpbin.org/put', data = {'key':'value'}) >>>r = requests.delete('http://httpbin.org/delete') >>>r = requests.head('http://httpbin.org/get') >>>r = requests.options('http://httpbin.org/get')
传递 URL 参数
>>>payload = {'key1': 'value1', 'key2': 'value2'}#值为None则不添加 >>>r = requests.get("http://httpbin.org/get",params=payload) >>>r.url #http://httpbin.org/get?key2=value2&key1=value1
响应内容
>>>import requests >>>r = requests.get('https://api.github.com/events') >>>r.text #u'[{"repository":{"open_issues":0,"url":"https://github.com/... >>>r.encoding#查看编码 #'utf-8' >>>r.encoding = 'ISO-8859-1'#设置编码,每次相应都以设置的编码响应 >>>r.content #二进制响应内容 >>>r.json()#JSON相应内容 >>>r.raw #原始响应内容 >>>r.status_code#响应状态码 >>> r.status_code == requests.codes.ok >>> r.raise_for_status()#如果是错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应)则抛出异常
定制请求头
header
值必须是string
、bytestring
或者unicode
>>>url = 'https://api.github.com/some/endpoint' >>>headers = {'user-agent': 'my-app/0.0.1'} >>>r = requests.get(url, headers=headers)
响应头
>>> r.headers#查看响应头 >>> r.headers['Content-Type'] #'application/json' >>> r.headers.get('content-type') #'application/json
Cookie
>>> url = 'http://example.com/some/cookie/setting/url' >>> r = requests.get(url) >>> r.cookies['example_cookie_name'] 'example_cookie_value' >>> url = 'http://httpbin.org/cookies' >>> cookies = dict(cookies_are='working')#设置 >>> r = requests.get(url, cookies=cookies)#发送 >>> r.text '{"cookies": {"cookies_are": "working"}}'
超时
>>> requests.get('http://github.com', timeout=1)
timeout 仅对连接过程有效,与响应体的下载无关
错误与异常
遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个
ConnectionError
异常如果 HTTP 请求返回了不成功的状态码,
Response.raise_for_status()
会抛出一个HTTPError
异常若请求超时,则抛出一个
Timeout
异常若请求超过了设定的最大重定向次数,则会抛出一个
TooManyRedirects
异常所有Requests显式抛出的异常都继承自
requests.exceptions.RequestException
-
python使用requests时报错requests.exceptions.SSLError: HTTPSConnectionPool
2017-08-13 14:23:13报错信息 Traceback (most recent call last): File "", line 1, in File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\api.py", line 72, in get return request('get', url, params报错信息
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\api.py", line 72, in get return request('get', url, params=params, **kwargs) File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\sessions.py", line 640, in send history = [resp for resp in gen] if allow_redirects else [] File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\sessions.py", line 218, in resolve_redirects **adapter_kwargs File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\adapters.py", line 506, in send raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='www.baidu.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)'),))
过程
测试1
不指定headers时GET:
>>> import requests >>> requests.get('http://www.baidu.com/') <Response [200]> >>> requests.get('http://www.baidu.com/') <Response [200]> >>> requests.get('http://www.baidu.com/') <Response [200]> >>> header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',} >>> requests.get('http://www.baidu.com/', headers = header) <Response [200]>
测试2
当指定headers的User-Agent为火狐浏览器时:
>>> header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',} >>> requests.get('http://www.baidu.com/', headers = header) <Response [200]> >>> requests.get('http://www.baidu.com/', headers = header) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\api.py", line 72, in get return request('get', url, params=params, **kwargs) File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\sessions.py", line 640, in send history = [resp for resp in gen] if allow_redirects else [] File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\sessions.py", line 218, in resolve_redirects **adapter_kwargs File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "D:\python\lib\site-packages\requests-2.18.3-py2.7.egg\requests\adapters.py", line 506, in send raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='www.baidu.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)'),))
分析
现象:第一次GET时正常,第二次GET时,会报错.
不同点:User-Agent不相同
分析:由于报错SSL证书验证失败,所以这次的访问应该是https协议.但是我们明明使用的是http,所以,猜测访问该网站后,被重定向到了https://www.baidu.com/
验证
首先,进行GET时,关闭证书验证.因为,如果不关闭,请求总是失败,不能获取到重定向的信息.
>>> response = requests.get('http://www.baidu.com/', headers = header, verify=False) D:\python\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) >>> response.history [<Response [302]>] >>> response.url u'https://www.baidu.com/'
当不指定User-Agent时
>>> response = requests.get('http://www.baidu.com/', verify=False) >>> response.history [] >>> response.url u'http://www.baidu.com/'
结论
当指定headers的User-Agent时,baidu的服务器会重定向到https的网址.因此报出SSL验证失败的错误.
解决方法
方法1:
在进行GET时,指定SSL证书.详情见附件
方法2:
关闭证书验证. 详情见附件
附件
[各浏览器的User-Agent] http://www.useragentstring.com/pages/useragentstring.php
[SSL 证书验证] https://requests.readthedocs.io/zh_CN/latest/user/advanced.html#ssl
-
Python-第三方库requests详解
2016-03-16 11:45:15Requests 是用Python语言编写,基于 urllib,采用 Apache2 ...Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。更重要的一点是它支持 Python3 哦! 希望我的博客对您有用。 阿...Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。更重要的一点是它支持 Python3 哦!
希望我的博客对您有用。
阿里云最高1888通用代金券,送给你!
- Beautiful is better than ugly.(美丽优于丑陋)
- Explicit is better than implicit.(清楚优于含糊)
- Simple is better than complex.(简单优于复杂)
- Complex is better than complicated.(复杂优于繁琐)
- Readability counts.(重要的是可读性)
一、安装 Requests
通过pip安装
pip install requests
或者,下载代码后安装:
$ git clone git://github.com/kennethreitz/requests.git $ cd requests $ python setup.py install
再懒一点,通过IDE安装吧,如pycharm!
二、发送请求与传递参数
先来一个简单的例子吧!让你了解下其威力:
import requests r = requests.get(url='http://www.itwhy.org') # 最基本的GET请求 print(r.status_code) # 获取返回状态 r = requests.get(url='http://dict.baidu.com/s', params={'wd':'python'}) #带参数的GET请求 print(r.url) print(r.text) #打印解码后的返回数据
很简单吧!不但GET方法简单,其他方法都是统一的接口样式哦!
requests.get(‘https://github.com/timeline.json’) #GET请求
requests.post(“http://httpbin.org/post”) #POST请求
requests.put(“http://httpbin.org/put”) #PUT请求
requests.delete(“http://httpbin.org/delete”) #DELETE请求
requests.head(“http://httpbin.org/get”) #HEAD请求
requests.options(“http://httpbin.org/get”) #OPTIONS请求PS:以上的HTTP方法,对于WEB系统一般只支持 GET 和 POST,有一些还支持 HEAD 方法。
带参数的请求实例:import requests requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'}) #GET参数实例 requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '测试POST'}) #POST参数实例
POST发送JSON数据:
import requests import json r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'})) print(r.json())
定制header:
import requests import json data = {'some': 'data'} headers = {'content-type': 'application/json', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers) print(r.text)
三、Response对象
使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,如上实例中已经提到的 r.text、r.status_code……
获取文本方式的响应体实例:当你访问 r.text 之时,会使用其响应的文本编码进行解码,并且你可以修改其编码让 r.text 使用自定义的编码进行解码。r = requests.get('http://www.itwhy.org') print(r.text, '\n{}\n'.format('*'*79), r.encoding) r.encoding = 'GBK' print(r.text, '\n{}\n'.format('*'*79), r.encoding)
其他响应:
r.status_code #响应状态码
r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
#*特殊方法*#
r.json() #Requests中内置的JSON解码器
r.raise_for_status() #失败请求(非200响应)抛出异常案例之一:
import requests URL = 'http://ip.taobao.com/service/getIpInfo.php' # 淘宝IP地址库API try: r = requests.get(URL, params={'ip': '8.8.8.8'}, timeout=1) r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常 except requests.RequestException as e: print(e) else: result = r.json() print(type(result), result, sep='\n')
四、上传文件
使用 Requests 模块,上传文件也是如此简单的,文件的类型会自动进行处理:
import requests url = 'http://127.0.0.1:5000/upload' files = {'file': open('/home/lyb/sjzl.mpg', 'rb')} #files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))} #显式的设置文件名 r = requests.post(url, files=files) print(r.text)
更加方便的是,你可以把字符串当着文件进行上传:
import requests url = 'http://127.0.0.1:5000/upload' files = {'file': ('test.txt', b'Hello Requests.')} #必需显式的设置文件名 r = requests.post(url, files=files) print(r.text)
五、身份验证
基本身份认证(HTTP Basic Auth):
import requests from requests.auth import HTTPBasicAuth r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd')) # r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd')) # 简写 print(r.json())
另一种非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的:
requests.get(URL, auth=HTTPDigestAuth('user', 'pass'))
六、Cookies与会话对象
如果某个响应中包含一些Cookie,你可以快速访问它们:
import requests r = requests.get('http://www.google.com.hk/') print(r.cookies['NID']) print(tuple(r.cookies))
要想发送你的cookies到服务器,可以使用 cookies 参数:
import requests url = 'http://httpbin.org/cookies' cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'} # 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。 r = requests.get(url, cookies=cookies) print(r.json())
会话对象让你能够跨请求保持某些参数,最方便的是在同一个Session实例发出的所有请求之间保持cookies,且这些都是自动处理的,甚是方便。
下面就来一个真正的实例,如下是快盘签到脚本:import requests headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept-Language': 'en-us;q=0.5,en;q=0.3', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} s = requests.Session() s.headers.update(headers) # s.auth = ('superuser', '123') s.get('https://www.kuaipan.cn/account_login.htm') _URL = 'http://www.kuaipan.cn/index.php' s.post(_URL, params={'ac':'account', 'op':'login'}, data={'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'}) r = s.get(_URL, params={'ac':'zone', 'op':'taskdetail'}) print(r.json()) s.get(_URL, params={'ac':'common', 'op':'usersign'})
七、超时与异常
timeout 仅对连接过程有效,与响应体的下载无关。
>>> requests.get('http://github.com', timeout=0.001) Traceback (most recent call last): File "<stdin>", line 1, in <module> requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。
转自:http://www.itwhy.org/%E8%BD%AF%E4%BB%B6%E5%B7%A5%E7%A8%8B/python/python-%E7%AC%AC%E4%B8%89%E6%96%B9-http-%E5%BA%93-requests-%E5%AD%A6%E4%B9%A0.html
requests是python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?官方文档中是这样说明的:
python的标准库urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一个简单的功能就需要一大堆代码。
我也看了下requests的文档,确实很简单,适合我这种懒人。下面就是一些简单指南。
插播个好消息!刚看到requests有了中文翻译版,建议英文不好的看看,内容也比我的博客好多了,具体链接是:http://cn.python-requests.org/en/latest/(不过是v1.1.0版,另抱歉,之前贴错链接了)。
1. 安装
安装很简单,我是win系统,就在这里下载了安装包(网页中download the zipball处链接),然后
$ python setup.py install
就装好了。
当然,有easy_install
或pip
的朋友可以直接使用:easy_install requests
或者pip install requests
来安装。
至于linux用户,这个页面还有其他安装方法。
测试:在IDLE中输入import requests
,如果没提示错误,那说明已经安装成功了!2. 小试牛刀
>>>import requests >>> r = requests.get('http://www.zhidaow.com') # 发送请求 >>> r.status_code # 返回码 200 >>> r.headers['content-type'] # 返回头部信息 'text/html; charset=utf8' >>> r.encoding # 编码信息 'utf-8' >>> r.text #内容部分(PS,由于编码问题,建议这里使用r.content) u'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml"...' ...
是不是很简单?比urllib2和urllib简单直观的多?!那请接着看快速指南吧。
3. 快速指南
3.1 发送请求
发送请求很简单的,首先要导入requests模块:
>>>import requests
接下来让我们获取一个网页,例如我个人博客的首页:
>>>r = requests.get('http://www.zhidaow.com')
接下来,我们就可以使用这个
r
的各种方法和函数了。
另外,HTTP请求还有很多类型,比如POST,PUT,DELETE,HEAD,OPTIONS。也都可以用同样的方式实现:>>> 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")
因为目前我还没用到这些,所以没有深入研究。
3.2 在URLs中传递参数
有时候我们需要在URL中传递参数,比如在采集百度搜索结果时,我们wd参数(搜索词)和rn参数(搜素结果数量),你可以手工组成URL,requests也提供了一种看起来很NB的方法:
>>> payload = {'wd': '张亚楠', 'rn': '100'} >>> r = requests.get("http://www.baidu.com/s", params=payload) >>> print r.url u'http://www.baidu.com/s?rn=100&wd=%E5%BC%A0%E4%BA%9A%E6%A5%A0'
上面
wd=
的乱码就是“张亚楠”的转码形式。(好像参数按照首字母进行了排序。)3.3 获取响应内容
可以通过
r.text
来获取网页的内容。>>> r = requests.get('https://www.zhidaow.com') >>> r.text u'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml"...'
文档里说,requests会自动将内容转码。大多数unicode字体都会无缝转码。但我在cygwin下使用时老是出现
UnicodeEncodeError
错误,郁闷。倒是在python的IDLE中完全正常。
另外,还可以通过r.content
来获取页面内容。>>> r = requests.get('https://www.zhidaow.com') >>> r.content b'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml"...'
文档中说
r.content
是以字节的方式去显示,所以在IDLE中以b
开头。但我在cygwin中用起来并没有,下载网页正好。所以就替代了urllib2的urllib2.urlopen(url).read()
功能。(基本上是我用的最多的一个功能。)3.4 获取网页编码
可以使用
r.encoding
来获取网页编码。>>> r = requests.get('http://www.zhidaow.com') >>> r.encoding 'utf-8'
当你发送请求时,requests会根据HTTP头部来猜测网页编码,当你使用
r.text
时,requests就会使用这个编码。当然你还可以修改requests的编码形式。>>> r = requests.get('http://www.zhidaow.com') >>> r.encoding 'utf-8' >>>r.encoding = 'ISO-8859-1'
像上面的例子,对encoding修改后就直接会用修改后的编码去获取网页内容。
3.5 json
像urllib和urllib2,如果用到json,就要引入新模块,如
json
和simplejson
,但在requests中已经有了内置的函数,r.json()
。就拿查询IP的API来说:>>>r = requests.get('http://ip.taobao.com/service/getIpInfo.php?ip=122.88.60.28') >>>r.json()['data']['country'] '中国'
3.6 网页状态码
我们可以用
r.status_code
来检查网页的状态码。>>>r = requests.get('http://www.mengtiankong.com') >>>r.status_code 200 >>>r = requests.get('http://www.mengtiankong.com/123123/') >>>r.status_code 404 >>>r = requests.get('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN') >>>r.url u'http://www.zhidaow.com/ >>>r.status_code 200
前两个例子很正常,能正常打开的返回200,不能正常打开的返回404。但第三个就有点奇怪了,那个是百度搜索结果中的302跳转地址,但状态码显示是200,接下来我用了一招让他原形毕露:
>>>r.history (<Response [302]>,)
这里能看出他是使用了302跳转。也许有人认为这样可以通过判断和正则来获取跳转的状态码了,其实还有个更简单的方法:
>>>r = requests.get('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN', allow_redirects = False) >>>r.status_code 302
只要加上一个参数
allow_redirects
,禁止了跳转,就直接出现跳转的状态码了,好用吧?我也利用这个在最后一掌做了个简单的获取网页状态码的小应用,原理就是这个。3.7 响应头内容
可以通过
r.headers
来获取响应头内容。>>>r = requests.get('http://www.zhidaow.com') >>> r.headers { 'content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'content-type': 'text/html; charset=utf-8'; ... }
可以看到是以字典的形式返回了全部内容,我们也可以访问部分内容。
>>> r.headers['Content-Type'] 'text/html; charset=utf-8' >>> r.headers.get('content-type') 'text/html; charset=utf-8'
3.8 设置超时时间
我们可以通过
timeout
属性设置超时时间,一旦超过这个时间还没获得响应内容,就会提示错误。>>> requests.get('http://github.com', timeout=0.001) Traceback (most recent call last): File "<stdin>", line 1, in <module> requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
3.9 代理访问
采集时为避免被封IP,经常会使用代理。requests也有相应的
proxies
属性。import requests proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080", } requests.get("http://www.zhidaow.com", proxies=proxies)
如果代理需要账户和密码,则需这样:
proxies = { "http": "http://user:pass@10.10.1.10:3128/", }
3.10 请求头内容
请求头内容可以用
r.request.headers
来获取。>>> r.request.headers {'Accept-Encoding': 'identity, deflate, compress, gzip', 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.3 CPython/2.7.3 Windows/XP'}
3.11 自定义请求头部
伪装请求头部是采集时经常用的,我们可以用这个方法来隐藏:
r = requests.get('http://www.zhidaow.com') print r.request.headers['User-Agent'] #python-requests/1.2.3 CPython/2.7.3 Windows/XP headers = {'User-Agent': 'alexkh'} r = requests.get('http://www.zhidaow.com', headers = headers) print r.request.headers['User-Agent'] #alexkh
3.12 持久连接keep-alive
requests的keep-alive是基于urllib3,同一会话内的持久连接完全是自动的。同一会话内的所有请求都会自动使用恰当的连接。
也就是说,你无需任何设置,requests会自动实现keep-alive。
4. 简单应用
4.1 获取网页返回码
def get_status(url): r = requests.get(url, allow_redirects = False) return r.status_code print get_status('http://www.zhidaow.com') #200 print get_status('http://www.zhidaow.com/hi404/') #404 print get_status('http://mengtiankong.com') #301 print get_status('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN') #302 print get_status('http://www.huiya56.com/com8.intre.asp?46981.html') #500
后记
1、官方文档
requests的具体安装过程请看:http://docs.python-requests.org/en/latest/user/install.html#install
requests的官方指南文档:http://docs.python-requests.org/en/latest/user/quickstart.html
requests的高级指南文档:http://docs.python-requests.org/en/latest/user/advanced.html#advanced
2、本文内容部分翻译自官方文档,部分自己归纳。
3、大多数用的IDLE格式,累死了,下次直接用编辑器格式,这样更符合我的习惯。
4、还是那句话,有问题留言或email。
5、图注:requests官方文档上的一只老鳖。转载出处:http://www.zhidaow.com/post/python-requests-install-and-brief-introduction
如果我的博客对您有用,请您务必扫码,您得红包,我也能得红包!谢谢!
希望我的博客对您有用。
阿里云最高1888通用代金券,送给你!
-
解决已经安装requests,却依然提示No module named ‘requests
2020-07-01 21:02:05pip install requests 之后依然提示 Python ImportError: No module named 'requests' 经过文件搜索和提示,发现是因为安装目录不正确。 一定要切到Python的主目录下安装。如果已经安装,那么找到现在的安装...Python版本3.5.1,
pip install requests 之后依然提示
Python ImportError: No module named 'requests'
经过文件搜索和提示,发现是因为安装目录不正确。一定要切到Python的主目录下安装requests。如果提示已经安装,那原因是安装的路径不正确,需要先卸载。找到现在的安装目录(会提示),在CMD窗口切过去,执行:pip uninstall requestsC:\Users\Administrator>pip uninstall requests
Uninstalling requests-2.14.2:
c:\programdata\anaconda3\lib\site-packages\requests
c:\programdata\anaconda3\lib\site-packages\requests-2.14.2-py3.6.egg-info
Proceed (y/n)? y
Successfully uninstalled requests-2.14.2然后,将目录切到Python的安装目录下,执行:pip install requests.会出现如下的提示:Collecting requests
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connec
tion broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.conne
ction.VerifiedHTTPSConnection object at 0x036C1850>: Failed to establish a new c
onnection: [Errno 11003] getaddrinfo failed',)': /simple/requests/
Downloading requests-2.18.3-py2.py3-none-any.whl (88kB)
46% |██████████████▉ | 40kB 251kB/s eta 0:00:
57% |██████████████████▌ | 51kB 268kB/s eta 0
69% |██████████████████████▏ | 61kB 315kB/s e
80% |█████████████████████████▉ | 71kB 341kB/
92% |█████████████████████████████▋ | 81kB 38
100% |████████████████████████████████| 92kB
359kB/s
Collecting urllib3<1.23,>=1.21.1 (from requests)
Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
38% |████████████▍ | 51kB 965kB/s eta 0:00:01
46% |██████████████▉ | 61kB 1.1MB/s eta 0:00:
54% |█████████████████▍ | 71kB 1.1MB/s eta 0:
61% |███████████████████▉ | 81kB 1.0MB/s eta
69% |██████████████████████▎ | 92kB 1.1MB/s e
77% |████████████████████████▊ | 102kB 1.1MB/
85% |███████████████████████████▎ | 112kB 1.0至此,问题解决。 -
python3下使用requests实现模拟用户登录 —— 基础篇(马蜂窝)
2018-03-15 17:20:17python3下使用requests实现模拟用户登录 —— 基础篇(马蜂窝) 1. 了解cookie和session 首先一定要先了解到cookie和session是什么,这是后面理解网站交互,模拟用户登录的基础。 1.1. 无状态协议:Http ... -
Pycharm 报No module named ‘requests‘错的解决办法
2019-07-01 15:32:221、首先检查是否安装了requests l安装命令: pip install requests 如果出现了Requirement already satisfied代表安装成功 l或pip list显示安装 2、PyCharm配置问题(项目的解释器配置问题) ①解决办法:... -
Requests基础用法
2018-09-26 14:56:11目录 发送请求 传递 URL 参数 响应内容 文本响应内容 二进制响应内容 JSON 响应内容 原始响应内容 ...使用 Requests 发送网络请求非常简单,支持的 HTTP 请求类型:GET,POST,PUT,DELE... -
ModuleNotFoundError: No module named 'requests'
2019-08-06 10:54:19Python: ImportRequestsError: No module named 'requests'解决方法 运行Python程序时,出现下面错误: import requests ModuleNotFoundError: No module named ‘requests’ 原因:没有导入requests库 解决... -
python requests 获取,设置cookie
2018-04-25 19:41:59python requests 获取,设置cookie 首先是有一个能返回cookie的url, 然后在获取, 如下: import requests url = "https://fanyi.baidu.com" res = requests.get(url) print res.cookies print type(res.cookies)... -
requests模块
2018-10-06 15:47:35requests 响应内容的处理 requests异常的处理 requests requests库是 python中非常优秀的第三方库(python2和python3中均有requests库),它使用 Apache2 Licensed 许可证的 HTTP 库,用 Python 编写。requests ... -
requests模块访问api接口小记,requests.request、requests.get和requests.post
2018-12-02 17:25:24用了些requests模块,主要是requests.request、requests.get和requests.post import json import requests url='http://localhost:8888/' response=requests.get(url) #打印响应内容 print('response.text:',... -
requests库
2019-07-27 15:54:45pip install requests 请求方式 requests.get(url) requests.post(url) requests.put(url) requests.delete(url) requests.head(url) requests.options(url) Session.request参数 method: 请求方式 如:get... -
Requests安装
2019-07-15 02:18:00Requests安装 pipenv安装 点击这里跳转URL pip安装 windows pip install requests linux sudo pip install requests -
import requests
2019-03-22 23:28:06requests是python实现...pip install requests 安装完成后import一下,正常则说明可以开始使用了。 基本用法: requests.get()用于请求目标网站,类型是一个HTTPresponse类型 import requests response = requests... -
python-requests伪装浏览器
2020-11-26 15:18:02在headers中添加 'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,...import requests url = 'https://blog.csdn.net/zy1007531447' headers = { 'user-agent':'Mozilla/5.0 -
python爬虫 requests异常requests.exceptions.ConnectionError: HTTPSConnectionPool Max retries exceeded
2018-10-25 17:28:56python爬虫 requests异常requests.exceptions.ConnectionError: HTTPSConnectionPool Max retries exceeded 错误提示: requests.exceptions.ConnectionError: HTTPSConnectionPool(host='baike.baidu.com',... -
Python Requests 小技巧总结
2016-10-11 20:17:00关于 Python Requests ,在使用中,总结了一些小技巧把,分享下。 1:保持请求之间的Cookies,我们可以这样做。 import requests self.session = requests.Session() self.session.get(login_url) # 可以保持... -
requests.text和requests.content的区别
2020-06-27 11:21:03我们在利用requests库进行网络数据爬取时,通常遇到编码问题,在通过requests的get方法获取响应后,通常有response.text和response.content两种输出格式: 1. response.content: 这个是直接从网络上面抓取的数据... -
Requests简单使用【python爬虫小课堂】
2020-05-23 02:48:39Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib 模块已经包含了...Requests 继承了urllib的所有特性。Requests支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码 -
python的requests发送/上传多个文件
2017-07-10 13:45:32在requests中发送文件的接口只有一种,那就是使用requests.post的files参数, 请求形式如下: url = "http://httpbin.org/post" data = None files = { ... } r = requests.post(url, data, files=f... -
数据爬虫(三):python中requests库使用方法详解
2018-02-02 04:55:41一、什么是Requests Requests 是⽤Python语⾔编写,基于urllib,采⽤Apache2 Licensed开源协议的 HTTP 库。它⽐ urllib 更加⽅便,可以节约我们⼤量的⼯作,完全满⾜HTTP测试需求。 ⼀句话——Python实现的简单易... -
Py之requests:python的requests包的简介、安装、使用方法详细攻略
2018-04-08 11:27:19Py之requests:python的requests包的简介、安装、使用方法详细攻略 目录 requests包的简介 requests包的安装 requests包的使用方法 requests包的简介 requests是为人类构建的Python的一个优雅而... -
Python requests timeout 分析
2020-09-26 12:58:28最近在搞爬虫,很多小组件里面都使用了 Python 的 requests 库,很好用,很强大。 但最近发现很多任务总是莫名其妙的卡住,不报错,但是就是不继续执行。 排查了一圈,最后把问题锁定在 requests 的 timeout 机制上... -
安装Requests
2018-10-31 23:46:55在python3中,可以使用urllib.request和requests进行网页爬取。 urllib是python内置的,只要安装了python就可以使用这个库。 安装Requests 打开cmd,输入: pip install requests 如果提示: Could not find...
-
【数据分析-随到随学】量化交易策略模型
-
安卓开发职位要求!一年后斩获腾讯T3,讲的明明白白!
-
jdk-8u161-windows-x64.exe
-
基于X210的裸机时钟温度显示器-第3/3季
-
双向链表
-
单片机完全学习课程全五季套餐
-
已解决:项目打完jar包后,无法读取src目录下的.properties文件
-
android-ffmpeg-4.0.6.zip
-
win远程多用户rdpwrap配置文件(6.0.6002.22790)
-
hbase资料_hbase-default.xml.zip
-
Java学习路线,好的学习路线和好的方法,能让我们少走些弯路
-
安卓开发网!关于网络优化你必须要知道的重点,面试心得体会
-
朱有鹏老师嵌入式linux核心课程2期介绍
-
微服务系列第七十一季-Spring入门
-
2021-01-19
-
FFmpeg4.3系列之26:视频监控之H265多路摄像头播控项目实战
-
verilog 16位有符号数乘法器
-
FDk三维图像重建投影数据--参考论文.zip
-
Km1(2.0)Setup.rar
-
【控制】《复杂运动体系统的分布式协同控制与优化》-方浩老师-第8章-固定翼飞行器的编队跟踪与姿态调节一体化控制