欢迎来到Cecilia陈的博客

孤独,是人一生最好的修行。

02 请求库之requests库

一、介绍

安装requests库

pip3 install requests

介绍:Requests

#介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)

#注意:requests库发送请求将网页内容下载下来以后,并不会执行js代码,这需要我们自己分析目标站点然后发起新的request请求

#各种请求方式:常用的就是requests.get()和requests.post()
>>> 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')

官网链接:https://docs.python-requests.org//en/master/

二、基于Get请求

1. 基本请求

import requests
response = requests.get('https://www.baidu.com')
print(response.status_code) # 响应状态码
print(response.text)#响应文本(str)内容

2.带参数的Get请求-->headers

通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常用的有用的请求头如下:
    Host
    Referer #大型网站通常会根据该参数判断请求的来源,请求当前url的上一个url
    User-Agent# 客户端,浏览器的标识
    Cookie #Cookie信息虽然包含在请求头里,但requests模块有单独的参数来处理他,headers={}内就不要放他了
#添加headers(浏览器会识别请求头,不加可能会被拒绝访问,比如访问https://www.zhihu.com/explore)
import requests
response=requests.get('https://www.zhihu.com/explore')
response.status_code #500


#自己定制headers
headers={
    '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',

}
respone=requests.get('https://www.zhihu.com/explore',
                     headers=headers)
print(respone.status_code) #200

3. 带参数的Get请求-->params

# urlencode的使用
#在请求头内将自己伪装成浏览器,否则百度不会正常返回页面内容
import requests
response=requests.get('https://www.baidu.com/s?wd=python',
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',         'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'
}
print(response.text)# 响应内容



#如果查询关键词是中文或者有其他特殊符号,则不得不进行url编码
from urllib.parse import urlencode
wd='小狗'
encode_res=urlencode({'k':wd},encoding='utf-8')
keyword=encode_res.split('=')[1]
print(keyword)
                      
# 然后拼接成url,既可以请求访问
url='https://www.baidu.com/s?wd=%s&pn=1' %keyword
# parmas参数的使用
#上述操作可以用requests模块的一个params参数搞定,本质还是调用urlencode
response=requests.get('https://www.baidu.com/s',params={'wd':'小狗'})

4. 带参数的Get请求-->cookies

#登录github,然后从浏览器中获取cookies,以后就可以直接拿着cookie登录了,无需输入用户名密码
# 首先我们得先登录一个GitHub账号

import requests
Cookies={   'user_session':'wGMHFJKgDcmRIVvcA14_Wrt_3xaUyJNsBnPbYzEL6L0bHcfc',
}

response=requests.get('https://github.com/settings/emails',
             cookies=Cookies) #github对请求头没有什么限制,我们无需定制user-agent,对于其他网站可能还需要定制

print('1158834013@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请求,模拟浏览器的登录行为

# 对于登录来说,应该输错用户名或者密码然后分析抓包流程,用脑子想一想,输对了浏览器就跳转了,还分析个啥,怎么都找不到包
'''
一 目标站点分析
    浏览器输入https://github.com/login
    然后输入错误的账号密码,抓包
    发现登录行为是post提交到:https://github.com/session
    而且请求头包含cookie
    而且请求体包含:
        commit:Sign in
        utf8:✓		
        authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ==
        login:'***@qq.com'
        password:'*****'
'''


'''
1.先分析 http 的请求流程
    - 请求url:
        Request URL: https://github.com/session

    - 请求方式:
        Request Method: POST

    - 请求头:
        - Referer: https://github.com/login
        - User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36


    - 请求体: (form data):
        commit: Sign in
        utf8: ✓
        authenticity_token: finQLn5TxHAabDmefQ2EbBXV27jDGlWm6DUu+u5u4J6QnPXBmkc76/QlDpx61v1NFf3AP8r+vg1Cq31G9Wxenw==
        ga_id:
        login: 335332932@qq.com
        password: Ai7071728109
        webauthn-support: supported
        webauthn-iuvpaa-support: supported
        required_field_a359:
        timestamp: 1577696492100  # 时间戳
        timestamp_secret: 03e50e82485174cadc2dda90916b93bfeadef0ac92643cbfde40e6c7f598bbb6


    - 1) 先往https://github.com/login页面发送get请求,获取authenticity_token与timestamp_secret随机加密字符串
    - 2) 携带加密字符串与请求体所有的信息,一并通过post请求访问https://github.com/session
'''

import requests
import re

# 1) 先往https://github.com/login页面发送get请求,获取authenticity_token与timestamp_secret随机加密字符串
url = 'https://github.com/login'
login_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
}

login_response = requests.get(url, headers=login_headers)


# 2)先解析获取authenticity_token与timestamp_secret, 通过re模块实现
authenticity_token = re.findall('<input type="hidden" name="authenticity_token" value="(.*?)" />',
                                login_response.text,
                                re.S)[0] # 返回的内容的是列表,所有取[0]

timestamp_secret = re.findall('<input type="hidden" name="timestamp_secret" value="(.*?)" class="form-control" />',
                              login_response.text,
                              re.S)[0]



# 3) 携带加密字符串与请求体所有的信息,一并通过post请求访问https://github.com/session

form_data = {
    'commit': 'Sign in',
    'utf8': '✓',
    'authenticity_token': authenticity_token,
    'ga_id': '',
    'login': '******.com',
    'password': '*****
    'webauthn-support': 'supported',
    'webauthn-iuvpaa-support': 'supported',
    'required_field_a359': '',
    'timestamp': 1577696892274,  # 时间戳
    'timestamp_secret': timestamp_secret
}
#
session_url = 'https://github.com/session'
session_response = requests.post(session_url,data=form_data,cookies=login_response.cookies
)


# 4) 登录后,直接访问github主页, 前提是需要携带登录成功后的用户cookies值
# 携带cookies值的两种方式:

index_response = requests.get('https://github.com/', cookies=session_response.cookies)
# print(index_response.text)
with open('github.html', 'w', encoding='utf-8') as f:
    f.write(index_response.text)


# 5) 验证是否登录成功,校验邮箱
emails_response = requests.get('https://github.com/settings/emails', cookies=session_response.cookies)
print('****.com' in emails_response.text)

3. 补充

requests.post(url='xxxxxxxx',
              data={'xxx':'yyy'}) #没有指定请求头,#默认的请求头:application/x-www-form-urlencoed

#如果我们自定义请求头是application/json,并且用data传值, 则服务端取不到值
requests.post(url='',
              data={'':1,},
              headers={
                  'content-type':'application/json'
              })

requests.post(url='',
              json={'':1,},
              ) #默认的请求头:application/json

四、响应Response

1. response属性

import requests
respone=requests.get('http://www.baidu.com')
# respone属性
print(respone.text)# str数据文本内容
print(respone.content)# 二进制(img/mp4)

print(respone.status_code)#响应数据的状态码
print(respone.headers) #获取响应头信息
print(respone.cookies)#获取响应的cookies对象
print(respone.cookies.get_dict())# 将cookies对象转换成字典dict
print(respone.cookies.items())# 将cookies对象转换成列表list

print(respone.url)
print(respone.history)

print(respone.encoding)

#关闭:response.close()
from contextlib import closing
with closing(requests.get('xxx',stream=True)) as response:
    for line in response.iter_content():
    pass

2. 响应编码问题

# 我们以百度的首页为例

import requests

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
}
response = requests.get('https://www.baidu.com', headers=headers)
print(response.text) # 在这里的时候我们就发现返回回来的数据是乱码的,不是我们可读的
# 响应编码格式(*******)
print(response.encoding) # 查看响应数据的编码格式
# 解决字符编码不对应导致的数据展示错乱问题
response.encoding = 'utf-8' # 将响应数据的编码格式改掉
print(response.encoding) 
print(response.text) # 这个时候,编码问题就解决了

3. 返回二进制数据

# 返回的二进制数据(*******)
# 一般用于爬取图片、视频、音频
response = requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1577799602757&di=85b5366f43dacddfccaf0a452fbc7400&imgtype=0&src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F02%2F57%2F15%2F59fb6fae6d10f_610.jpg')
print(response.status_code) # 响应状态码
print(response.content) # 获取二进制数据

# 数据量较小的情况,
with open('dog.jpg','wb')as fw: # 将拿到的二进制数据进行持久化存储
    fw.write(response.content)

# 在数据量过大的时候
with open('dog1.jpg', 'wb') as f:
    # iter_content: 将二进制数据装进一个迭代器中
    for line in response.iter_content():
        f.write(line)    

print(response.url)# 获取当前网站的url地址

4. 解析json

#获取网站返回的json数据
import json
response = requests.get('https://landing.toutiao.com/api/pc/realtime_news/') #这个网址的返回内容就是json数据
print(response.status_code) # 返回响应数据状态码
# print(response.text)# 返回响应的文本内容json格式的
# print(json.loads(response.text))# 方式一 :序列化成字典
print(response.json())# 方式二:序列化成字典,推荐使用

五、requests高级使用

1. Https--ssl

import requests

''' 1、SSL (超级了解)--证书验证(大部分网站都是https)'''
''' http和https的区别:https是在http基础上加了ssl加密验证的'''
# response = requests.get('https://www.gaokao.com/gkpic/') #如果是ssl请求,首先检查证书是否合法,不合法则报错,程序终端
# 方法一:去掉报错(verify=False),但是会报警告
# response = requests.get('https://www.gaokao.com/gkpic/', verify=False) #不验证证书,报警告,返回200
# print(response.status_code)

# 方法二:去掉报错,并且去掉警报信息
# import urllib3  # python内置的模块 --- requests的前身,urllib --- urllib2 ---> urllib3
# urllib3.disable_warnings()  # 关闭警告
# response = requests.get('https://www.gaokao.com/gkpic/', verify=False)
# print(response.status_code)

# 方法三:加上证书
# #很多网站都是https,但是不用证书也可以访问,大多数情况都是可以携带也可以不携带证书
# #知乎\百度等都是可带可不带
# #有硬性要求的,则必须带,比如对于定向的用户,拿到证书后才有权限访问某个特定网站

# response=requests.get('https://www.12306.cn',
#                      # cert=(证书的文件路径),证书是必须真实存在的;
#                      cert=('/path/server.crt',
#                            '/path/key'))
# print(response.status_code)

2. 使用代理

# 官网链接: http://docs.python-requests.org/en/master/user/advanced/#proxies
# 代理设置:先发送请求给代理,然后由代理帮忙发送(封ip是常见的事情)
import requests
proxies = {
    # 'http': 'http://lala:123@localhost:8888',  # 带用户名密码的代理,@符号前是用户名与密码
    # 'http': 'http://localhost:9743',
    'https': '163.204.242.181:9999',
}
#
# response = requests.get('https://www.baidu.com/',
#                         # proxies: = 代理字典
#                         proxies=proxies)
#
# print(response.status_code)


# #支持socks代理,安装:pip install requests[socks]
# import requests
# proxies = {
#     'http': 'socks5://user:pass@host:port',
#     'https': 'socks5://user:pass@host:port'
# }
# respone=requests.get('https://www.12306.cn',
#                      proxies=proxies)
#
# print(respone.status_code)

3. 超时设置

#超时设置(超过时间以后会自动结束,不会等待)
#两种超时:float or tuple
#timeout=0.1 #代表接收数据的超时时间
#timeout=(0.1,0.2)#0.1代表链接超时  0.2代表接收数据的超时时间

 import requests
 try:
     response = requests.get('https://www.baidu.com', timeout=0.0001)

 except Exception as e:
     print(e)

4. 上传文件

'''4、上传文件'''
import requests
response = requests.post(
    'http://httpbin.org/post',
    files={
        'file': open(r'E:\python folder\Request\response响应信息\dog.jpg', 'rb')
    }
)

print(response.status_code)
posted @ 2020-01-05 19:04  Cecilia陈  阅读(184)  评论(0编辑  收藏  举报