请求库之 requests模块

介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)
#注意:requests库发送请求将网页内容下载下来以后,并不会执行js代码,这需要我们自己分析目标站点然后发起新的request请求
#安装:pip3 install requests
  1 #各种请求方式:常用的就是requests.get()和requests.post()
  2 >>> import requests
  3 >>> r = requests.get('https://api.github.com/events')
  4 >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
  5 >>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})
  6 >>> r = requests.delete('http://httpbin.org/delete')
  7 >>> r = requests.head('http://httpbin.org/get')
  8 >>> r = requests.options('http://httpbin.org/get')
  9 
 10 #建议在正式学习requests前,先熟悉下HTTP协议
 11 https://www.cnblogs.com/lz1996/p/11574058.html

二、基于GET请求

1、基本请求

  1 import requests
  2 response=requests.get('http:/www.baidu.com/')
  3 print(response.text)
2、带参数的GET请求->params
自己拼接GET参数
  1 #在请求头内将自己伪装成浏览器,否则百度不会正常返回页面内容
  2 import requests
  3 
  4 url = 'https://www.baidu.com/s?wd=python&pn=1'
  5 headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36'}
  6 
  7 response=requests.get(url=url, headers=headers)
  8 print(response.text)
  9 
 10 
 11 #如果查询关键词是中文或者有其他特殊符号,则不得不进行url编码
 12 from urllib.parse import urlencode
 13 wb = "中国"
 14 encode_res = urlencode({"k":wb},encoding="utf-8")
 15 print(encode_res)
 16 keywords = encode_res.split("=")[1]  #haiyan%E6%B5%B7%E7%87%95
 17 url = "https://www.baidu.com/s?wd=%s&pn=1"%(keywords)
 18 # url = "https://www.baidu.com/s?"+encode_res
 19 print(url)
 20 # 然后拼接成url
 21 headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36"}
 22 response = requests.get(url=url, headers=headers)
 23 
 24 
params参数的使用
  1 #上述操作可以用requests模块的一个params参数搞定,本质还是调用urlencode
  2 from urllib.parse import urlencode
  3 wd='中国'
  4 pn=1
  5 url = 'https://www.baidu.com/s'
  6 headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
  7 response=requests.get(url=url, headers=headers, params={'wd':wd,'pn':pn})
  8 res2=response.text
  9 
 10 #验证结果,打开a.html与b.html页面内容一样
 11 with open('a.html','w',encoding='utf-8') as f:
 12     f.write(res1)
 13 with open('b.html', 'w', encoding='utf-8') as f:
 14     f.write(res2)
 15 
3、带参数的GET请求->headers
通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常见的有用的请求头如下
Host
Referer #大型网站通常都会根据该参数判断请求的来源
User-Agent #客户端
Cookie #Cookie信息虽然包含在请求头里,但requests模块有单独的参数来处理他,headers={}内就不要放它了
  1 #添加headers(浏览器会识别请求头,不加可能会被拒绝访问,比如访问https://www.zhihu.com/explore)
  2 import requests
  3 response=requests.get('https://www.zhihu.com/explore')
  4 response.status_code #500
  5 
  6 
  7 #自己定制headers
  8 headers={
  9     'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36',
 10 
 11 }
 12 respone=requests.get('https://www.zhihu.com/explore',
 13                      headers=headers)
 14 print(respone.status_code) #200
4、带参数的GET请求->cookies
  1 #登录github,然后从浏览器中获取cookies,以后就可以直接拿着cookie登录了,无需输入用户名密码
  2 #用户名:egonlin 邮箱147xxxxxx@qq.com 密码********
  3 
  4 import requests
  5 
  6 Cookies={'user_session':'wGMHFJKgDcmRIVvcA14_Wrt_3xaUyJNsBnPbYzEL6L0bHcfc'}
  7 
  8 response=requests.get('https://github.com/settings/emails',
  9              cookies=Cookies) #github对请求头没有什么限制,我们无需定制user-agent,对于其他网站可能还需要定制
 10 
 11 
 12 print('147xxxxxx@qq.com' in response.text) #True

三、基于POST请求

1、介绍

#GET请求
HTTP默认的请求方法就是GET
      * 没有请求体
      * 数据必须在1K之内!
      * GET请求数据会暴露在浏览器的地址栏中

GET请求常用的操作:
        1. 在浏览器的地址栏中直接给出URL,那么就一定是GET请求
        2. 点击页面上的超链接也一定是GET请求
        3. 提交表单时,表单默认使用GET请求,但可以设置为POST


#POST请求
(1). 数据不会出现在地址栏中
(2). 数据的大小没有上限
(3). 有请求体
(4). 请求体中如果存在中文,会使用URL编码!


#!!!requests.post()用法与requests.get()完全一致,特殊的是requests.post()有一个data参数,用来存放请求体数据

2、发送post请求,模拟浏览器的登录行为

注意:
 1、对于登录来说,应该输错用户名或密码然后分析抓包流程,用脑子想一想,输对了浏览器就跳转了,还分析个毛线,累死你也找不到包

  2、要做登录的时候一定记得要把cookie先清除;
  3、requests.session():中间的cookie都不用自己分析了,有用的没用的都给放进来了、
  4、response.cookie.get_dict()    #获取cookie

自动登录github(自己处理cookie信息)

  1 '''
  2 一 目标站点分析
  3     浏览器输入https://github.com/login
  4     然后输入错误的账号密码,抓包
  5     发现登录行为是post提交到:https://github.com/session
  6     而且请求头包含cookie
  7     而且请求体包含:
  8         commit:Sign in
  9         utf8:✓
 10         authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ==
 11         login:egonlin
 12         password:123
 13 
 14 二 流程分析
 15     先GET:https://github.com/login拿到初始cookie与authenticity_token
 16     返回POST:https://github.com/session, 带上初始cookie,带上请求体(authenticity_token,用户名,密码等)
 17     最后拿到登录cookie
 18     ps:如果密码时密文形式,则可以先输错账号,输对密码,然后到浏览器中拿到加密后的密码,github的密码是明文
 19 '''
 20 import requests
 21 import re
 22 
 23 #第一次请求
 24 r1 = requests.get('https://github.com/login')
 25 r1_cookie = r1.cookies.get_dict() #拿到初始cookie(未被授权)
 26 authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN
 27 
 28 #第二次请求:带着初始cookie和TOKEN发送POST请求给登录页面,带上账号密码
 29 data = {
 30     'commit':'Sign in',
 31     'utf8':'✓',
 32     'authenticity_token':authenticity_token,
 33     'login':'317828332@qq.com',
 34     'password':'alex3714'
 35 }
 36 r2 = requests.post('https://github.com/session',
 37              data = data, cookies = r1_cookie)
 38 
 39 login_cookie = r2.cookies.get_dict()
 40 
 41 
 42 #第三次请求:以后的登录,拿着login_cookie就可以,比如访问一些个人配置
 43 r3 = requests.get('https://github.com/settings/emails',cookies = login_cookie)
 44 
 45 print('147xxxxxxxx2@qq.com' in r3.text) #True
 46 
 47 自动登录github(自己处理cookie信息)
 48 
 49 自动登录github(自己处理cookie信息)
 requests.session()自动帮我们保存cookie信息
  1 import requests
  2 import re
  3 
  4 session = requests.session()
  5 #第一次请求
  6 r1=session.get('https://github.com/login')
  7 authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN
  8 
  9 #第二次请求
 10 data={
 11     'commit':'Sign in',
 12     'utf8':'✓',
 13     'authenticity_token':authenticity_token,
 14     'login':'147xxxxxx2@qq.com',
 15     'password':'********'
 16 }
 17 r2 = session.post('https://github.com/session',data=data)
 18 
 19 #第三次请求
 20 r3 = session.get('https://github.com/settings/emails')
 21 
 22 print('147xxxxxxx@qq.com' in r3.text) #True

  1 import requests
  2 import re
  3 #第一次请求
  4     # GET请求
  5     # 请求头
  6     #    - 获取token和
  7     #    - User-agent
  8     #    - cookie
  9 # 第二次请求
 10     #POST请求
 11     #请求头
 12         # referer
 13         # User-agent
 14     #请求体
 15         #获取data
 16 # 第三次请求,登录成功之后
 17     #- 请求之前自己先登录一下,看一下有没有referer
 18     #- 请求新的url,进行其他操作
 19     #- 查看用户名在不在里面
 20 #第一次请求
 21 response1 = requests.get(
 22     "https://github.com/login",
 23     headers = {
 24         "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
 25     },
 26 )
 27 authenticity_token = re.findall('name="authenticity_token".*?value="(.*?)"',response1.text,re.S)
 28 r1_cookies =  response1.cookies.get_dict()
 29 # print(r1_cookies,"cookie")  #获取到的cookie
 30 
 31 #第二次请求
 32 response2 = requests.post(
 33     "https://github.com/session",
 34     headers = {
 35         "Referer": "https://github.com/",
 36         "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
 37     },
 38     data={
 39             "commit":"Sign in",
 40             "utf8":"",
 41             "authenticity_token":authenticity_token,
 42             "login":"haiyanzzz",
 43             "password":"xxxx",
 44 zhy..azjash1234
 45     },
 46     cookies = r1_cookies
 47 )
 48 print(response2.status_code)
 49 print(response2.history)  #跳转的历史状态码
 50 
 51 #第三次请求,登录成功之后,访问其他页面
 52 r2_cookies = response2.cookies.get_dict()  #拿上cookie,知道是你登录了,就开始访问页面
 53 response3 = requests.get(
 54     "https://github.com/settings/emails",
 55     headers = {
 56         "Referer": "https://github.com/",
 57         "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
 58     },
 59     cookies = r2_cookies,
 60 )
 61 print(response3.text)
 62 print("haiyanzzz" in response3.text)   #True返回True说明就成功了
登录github小应用 View Code
3、补充
  1 requests.post(url='xxxxxxxx',
  2               data={'xxx':'yyy'}) #没有指定请求头,#默认的请求头:application/x-www-form-urlencoed
  3 
  4 #如果我们自定义请求头是application/json,并且用data传值, 则服务端取不到值
  5 requests.post(url='',headers={'content-type':'application/json'},data={'':1,},)
  6 
  7 requests.post(url='',json={'':1,},) #默认的请求头:application/json

四、响应Response

1、response属性

  1 import requests
  2 respone=requests.get('http://www.jianshu.com')
  3 # respone属性
  4 print(respone.text)
  5 print(respone.content)
  6 
  7 print(respone.status_code)
  8 print(respone.headers)
  9 print(respone.cookies)
 10 print(respone.cookies.get_dict())
 11 print(respone.cookies.items())
 12 
 13 print(respone.url)
 14 print(respone.history)
 15 
 16 print(respone.encoding)
 17 
 18 #关闭:response.close()
 19 from contextlib import closing
 20 with closing(requests.get('xxx',stream=True)) as response:
 21     for line in response.iter_content():
 22     pass

2、编码问题

  1 #编码问题
  2 import requests
  3 response=requests.get('http://www.autohome.com/news')
  4 # response.encoding='gbk' #汽车之家网站返回的页面内容为gb2312编码的,而requests的默认编码为ISO-8859-1,如果不设置成gbk则中文乱码
  5 print(response.text)

3、获取二进制数据

  1 import requests
  2 
  3 response=requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509868306530&di=712e4ef3ab258b3
  4 6e9f4b48e85a81c9d&imgtype=0&src=http%3A%2F%2Fc.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F11385343fbf2b211e1fb58a1c08065380dd78e0c.jpg')
  5 
  6 with open('a.jpg','wb') as f:
  7     f.write(response.content)
stream参数:一点一点的取,比如下载视频时,如果视频100G,用response.content然后一下子写到文件中是不合理的
  1 #stream参数:一点一点的取,比如下载视频时,如果视频100G,用response.content然后一下子写到文件中是不合理的
  2 
  3 import requests
  4 
  5 response=requests.get('https://gss3.baidu.com/6LZ0ej3k1Qd3ote6lo7D0j9wehsv/tieba-smallvideo-transcode/1767502_56ec685f9c7ec542eeaf6eac93a65dc7_6fe25cd1347c_3.mp4',
  6                       stream=True)
  7 
  8 with open('b.mp4','wb') as f:
  9     for line in response.iter_content():
 10         f.write(line)
 11 
 12 

4、解析json

  1 #解析json
  2 import requests
  3 response = requests.get('http://httpbin.org/get')
  4 
  5 import json
  6 res1 = json.loads(response.text) #太麻烦
  7 res2 = response.json() #直接获取json数据
  8 
  9 print(res1 == res2) #True
5、Redirection and History
  1 By default Requests will perform location redirection for all verbs except HEAD.
  2 
  3 We can use the history property of the Response object to track redirection.
  4 
  5 The Response.history list contains the Response objects that were created in order to complete the request. The list is sorted from the oldest to the most recent response.
  6 
  7 For example, GitHub redirects all HTTP requests to HTTPS:
  8 
  9 >>> r = requests.get('http://github.com')
 10 
 11 >>> r.url
 12 'https://github.com/'
 13 
 14 >>> r.status_code
 15 
 16 >>> r.history
 17 [<Response [301]>]
 18 If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable redirection handling with the allow_redirects parameter:
 19 
 20 >>> r = requests.get('http://github.com', allow_redirects=False)
 21 
 22 >>> r.status_code
 23 
 24 >>> r.history
 25 []
 26 If you're using HEAD, you can enable redirection as well:
 27 
 28 >>> r = requests.head('http://github.com', allow_redirects=True)
 29 
 30 >>> r.url
 31 'https://github.com/'
 32 
 33 >>> r.history
 34 [<Response [301]>]
 35 
 36 
View Code
  1 import requests
  2 import re
  3 
  4 #第一次请求
  5 r1=requests.get('https://github.com/login')
  6 r1_cookie=r1.cookies.get_dict() #拿到初始cookie(未被授权)
  7 authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN
  8 
  9 #第二次请求:带着初始cookie和TOKEN发送POST请求给登录页面,带上账号密码
 10 data={
 11     'commit':'Sign in',
 12     'utf8':'✓',
 13     'authenticity_token':authenticity_token,
 14     'login':'317828332@qq.com',
 15     'password':'alex3714'
 16 }
 17 
 18 
 19 #测试一:没有指定allow_redirects=False,则响应头中出现Location就跳转到新页面,r2代表新页面的response
 20 r2=requests.post('https://github.com/session',
 21              data=data,
 22              cookies=r1_cookie
 23              )
 24 
 25 print(r2.status_code) #200
 26 print(r2.url) #看到的是跳转后的页面
 27 print(r2.history) #看到的是跳转前的response
 28 print(r2.history[0].text) #看到的是跳转前的response.text
 29 
 30 
 31 #测试二:指定allow_redirects=False,则响应头中即便出现Location也不会跳转到新页面,r2代表的仍然是老页面的response
 32 r2=requests.post('https://github.com/session',
 33              data=data,
 34              cookies=r1_cookie,
 35              allow_redirects=False
 36              )
 37 
 38 print(r2.status_code) #302
 39 print(r2.url) #看到的是跳转前的页面https://github.com/session
 40 print(r2.history) #[]
 41 
利用github登录后跳转到主页面的例子来验证它View Code

五、高级用法

1、SSL Cert Verification

  1 #证书验证(大部分网站都是https)
  2 import requests
  3 respone=requests.get('https://www.12306.cn') #如果是ssl请求,首先检查证书是否合法,不合法则报错,程序终端
  4 
  5 
  6 #改进1:去掉报错,但是会报警告
  7 import requests
  8 respone=requests.get('https://www.12306.cn',verify=False) #不验证证书,报警告,返回200
  9 print(respone.status_code)
 10 
 11 
 12 #改进2:去掉报错,并且去掉警报信息
 13 import requests
 14 from requests.packages import urllib3
 15 urllib3.disable_warnings() #关闭警告
 16 respone=requests.get('https://www.12306.cn',verify=False)
 17 print(respone.status_code)
 18 
 19 #改进3:加上证书
 20 #很多网站都是https,但是不用证书也可以访问,大多数情况都是可以携带也可以不携带证书
 21 #知乎百度等都是可带可不带
 22 #有硬性要求的,则必须带,比如对于定向的用户,拿到证书后才有权限访问某个特定网站
 23 import requests
 24 respone=requests.get('https://www.12306.cn',
 25                      cert=('/path/server.crt',
 26                            '/path/key'))
 27 print(respone.status_code)
2、使用代理
  1 #官网链接: http://docs.python-requests.org/en/master/user/advanced/#proxies
  2 
  3 #代理设置:先发送请求给代理,然后由代理帮忙发送(封ip是常见的事情)
  4 import requests
  5 proxies={
  6     'http':'http://egon:123@localhost:9743',#带用户名密码的代理,@符号前是用户名与密码
  7     'http':'http://localhost:9743',
  8     'https':'https://localhost:9743',
  9 }
 10 respone=requests.get('https://www.12306.cn',
 11                      proxies=proxies)
 12 
 13 print(respone.status_code)
 14 
 15 
 16 
 17 #支持socks代理,安装:pip install requests[socks]
 18 import requests
 19 proxies = {
 20     'http': 'socks5://user:pass@host:port',
 21     'https': 'socks5://user:pass@host:port'
 22 }
 23 respone=requests.get('https://www.12306.cn',
 24                      proxies=proxies)
 25 
 26 print(respone.status_code)
View Code
3、超时设置
  1 #超时设置
  2 #两种超时:float or tuple
  3 #timeout=0.1 #代表接收数据的超时时间
  4 #timeout=(0.1,0.2)#0.1代表链接超时  0.2代表接收数据的超时时间
  5 
  6 import requests
  7 respone=requests.get('https://www.baidu.com',
  8                      timeout=0.0001)
4、 认证设置
  1 #官网链接:http://docs.python-requests.org/en/master/user/authentication/
  2 
  3 #认证设置:登陆网站是,弹出一个框,要求你输入用户名密码(与alter很类似),此时是无法获取html的
  4 # 但本质原理是拼接成请求头发送
  5 #         r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
  6 # 一般的网站都不用默认的加密方式,都是自己写
  7 # 那么我们就需要按照网站的加密方式,自己写一个类似于_basic_auth_str的方法
  8 # 得到加密字符串后添加到请求头
  9 #         r.headers['Authorization'] =func('.....')
 10 
 11 #看一看默认的加密方式吧,通常网站都不会用默认的加密设置
 12 import requests
 13 from requests.auth import HTTPBasicAuth
 14 r=requests.get('xxx',auth=HTTPBasicAuth('user','password'))
 15 print(r.status_code)
 16 
 17 #HTTPBasicAuth可以简写为如下格式
 18 import requests
 19 r=requests.get('xxx',auth=('user','password'))
 20 print(r.status_code)
5、异常处理
  1 #异常处理
  2 import requests
  3 from requests.exceptions import * #可以查看requests.exceptions获取异常类型
  4 
  5 try:
  6     r = requests.get('http://www.baidu.com',timeout=0.00001)
  7 except ReadTimeout:
  8     print('===:')
  9 # except ConnectionError: #网络不通
 10 #     print('-----')
 11 # except Timeout:
 12 #     print('aaaaa')
 13 
 14 except RequestException:
 15     print('Error')
6、上传文件
  1 import requests
  2 
  3 files = {'file':open('a.jpg','rb')}
  4 respone=requests.post('http://httpbin.org/post',files=files)
  5 print(respone.status_code)


归类 : python爬虫
原文地址:https://www.cnblogs.com/lz1996/p/12040280.html