目录
Requests
作用:发送网络请求,获取响应数据
Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库
它比urllib更加方便,可以节约大量的工作,完全满足HTTP测试需求的库
安装命令:pip install requests
一、Requests请求
1、实例
import requests
response = requests.get('网站地址')
# 响应体对象(响应源码+响应状态码+响应URL)
print(response)
# 查看响应体内容
print(response.text)
# 查看响应内容的数据类型
print(type(rersponse.text))
# 查看响应状态码
print(response.status_code)
# 查看响应url
print(response.url)
2、各种请求方式
# GET请求
requests.get('http://httpbin.org/get')
requests.get('https://api.github.com/events')
# POST请求
requests.post('http://httpbin.org/post', data = {'key': 'value'})
requests.put('http://httpbin.org/put', data = {'key': 'value'})
requests.delete('http://httpbin.org/deleete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')
3、GET请求
1.基本写法
# 测试网站: http://httpbin.org/get
url = 'http://httpbin.org/get' # 目标站点
response = requests.get(url)
print(response.status_code) # 获取状态码
print(response.text) # 获取响应内容
print(type(response.text)) # str
2.带参数的get请求
# 测试网站: http://httpbin.org/get
# 第一种写法
一些网站地址中包含很多参数
url = 'http://httpbin.org/get?name=lisi&age=10'
response = requests.get(url)
print(response.status_code)
print(response.text
# 第二种写法(推荐写法)
将参数单独构建在字典中
data = {
'name': 'lsis',
'age': 10
}
url = 'http://httpbin.org/get'
response = requests.get(url, params = data) # params: 携带get请求的参数
print(response.text)
4、POST请求
# 测试网站: http://httpbin.org/post
# 这个直接打不开的,因为浏览器不能直接打开post请求,虽然不能直接打开,但可以通过代码测试
url = 'http://httpbin.org/post'
da = {'lisi': 10}
response = requests.post(url, data = da) # data:携带post请求的参数
print(response.text)
GET请求和POST请求传递参数的方式不一样,get是通过params传递的一给构建的字典参数,post是通过data传递的,这是开发人员定的。
5、获取json数据
import requests
import json
url = 'http://httpbin.org/get'
response = requests.get(url)
print(response.status_code) # 查看响应状态码
a= response.text
# print(a)
# print(type(a)) # 查看数据类型, 字符串, 只要是通过text获取的数据都是字符串
# 长得像字典的字符串,就是json数据
# 直接取出数据(如url), 先要转成字典,使用json模块
dict_data = json.loads(a) # str转成dict
print(dict_data)
print(type(dict_data))
result = dict_data['headers']['User-Agent']
print(result)
# 使用.json()方法直接获取json数据形式的源码,数据类型是dict,与json模块和方法不一样
json_data = response.json()
print(json_data)
print(type(json_data))
6、.content获取二进制数据
二进制 :
bytes类型是指一堆字节的集合,在python中以b开头的字符串都是bytes类型
Bytes类型的作用:
1. 在python中,数据转换成二进制后不是直接以010110100的形式表示的,而是用一种叫做bytes(字节)的类型来表示
2. 计算机只能储存二进制,而我们的字符、图片、视频、音乐等想存到硬盘上,也必须以正确的方式编码成二进制后再存
记住一句话:再python中,字符串必须编码成bytes后才能存到硬盘上
==》目标网站 ------- 百度logo图片,url为 https://www.baidu.com/img/baidu_jgylogo3.gif
url = 'https://www.baidu.com/img/baidu_jgylogo3.gif'
response = requests.get(url)
print(response.text)
print(type(response.text))
#* 获取二进制数据时,一般不用text属性获取,而是用content属性专门获取二进制数据
获取百度图片并保存至电脑本地
url = 'https://www.baidu.com/img/baidu_jgylogo3.gif'
response = requests.get(url) # 0101010101
print(response.content) # content :获取二进制数据
print(type(response.content))
保存图片:
data = response.content
with open('badu.png', 'wb') as f: # 也可以是 .gif
f.write(data)
获取正常文本数据用text属性;获取json数据用 .json()方法;获取二进制数据用content属性
7、初步伪装小爬虫 --->添加headers
浏览器用户身份的标识,缺少的话服务器会认为你不是一个正常的浏览器用户,而是一个爬虫系统
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
# 目标站点 -- 知乎:发现 - 知乎
用浏览器访问,演示完整的爬虫流程,先抓包,然后看response数据对比,虽然请求成功了,但是不代表每次都可以。
url = '发现 - 知乎'
response = requests.get(url)
print(response.status_code)
print(response.text)
# 组建身份信息, 复制浏览器中的请求报文中的User-Agent,注意的是复制粘贴的时候必须是字典形式。
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
}
response = requests.get(url, headers = headers) # headers :携带伪装参数
print(response.status_code)
print(response.text)
二、Response响应
1、response属性
#* 目标网站 -- http://www.jianshu.com
演示不携带User-Agent的时候会报错
import requests url = 'http://www.jianshu.com' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36' } response = requests.get(url, headers = headers) print(response.status_code) # 查看响应状态码 print(response.headers) # 查看响应头信息 print(response.url) # 查看url print(response.history) # 查看网页是否跳转 # 禁止网页跳转 ===> allow_redirects = False
2、状态码
#*
200 请求成功
404 页面没有找到
301、302 请求发生跳转
500、502、503 服务器内部错误# Redirection.(重定向)
300: ('multiple_choices') # (多种选择)针对请求,服务器可执行多种操作
301: ('moved_permanently', 'moved', '\\o-') # (永久移动)请求的网页已永久移动到新位置
302: ('found') # (临时移动)服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来响应以后的请求
303: ('see_other', 'other') # (查看其他位置)请求者应当对不同的位置使用单独的 GET 请求来检索响应时,服务器返回此代码
304: ('not_modified') # (未修改)自从上次请求后,请求的网页未修改过。服务器返回此响应时,不会返回网页内容
305: ('use_proxy') # (使用代理)请求者只能使用代理访问请求的网页
306: ('switch_proxy')
307: ('temporary_redirect', 'temporary_moved', 'temporary') # (临时重定向)服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来响应以后的请求
308: ('permanent_redirect', 'resume_incomplete', 'resume')
# These 2 to be removed in 3.0# Client Error.(客户端错误)
400: ('bad_request', 'bad') # 请求语法错误
401: ('unauthorized) # 客户试图未经授权访问受密码保护的页面
402: ('payment_required', 'payment')
403: ('forbidden')
404: ('not_found', '-o-') # 无法找到指定位置的资源
405: ('method_not_allowed', 'not_allowed') # 请求方法(GET、POST、HEAD、Delete、PUT、TRACE等)对指定的资源不适用
406: ('not_acceptable')
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication')
408: ('request_timeout', 'timeout')
409: ('conflict')
410: ('gone')411: ('length_required')
412: ('precondition_failed', 'precondition')
413: ('request_entity_too_large')
414: ('request_uri_too_large')
415: ('unsupported_media_type', 'unsupported_media', 'media_type')
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable')
417: ('expectation_failed')
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot')
421: ('misdirected_request')
422: ('unprocessable_entity', 'unprocessable')
423: ('locked')
424: ('failed_dependency', 'dependency')
425: ('unordered_collection', 'unordered')
426: ('upgrade_required', 'upgrade')
428: ('precondition_required', 'precondition')
429: ('too_many_requests', 'too_many')
431: ('header_fields_too_large', 'fields_too_large')
444: ('no_response', 'none')
449: ('retry_with', 'retry')
450: ('blocked_by_windows_parental_controls', 'parental_controls')
451: ('unavailable_for_legal_reasons', 'legal_reasons')
499: ('client_closed_request')# Server Error.(服务器错误)
500: ('internal_server_error', 'server_error', '/o\\', '✗') # 服务器遇到了意料不到的情况,不能完成客户的请求。
501: ('not_implemented') # 服务器不支持实现请求所需要的功能
502: ('bad_gateway') # 服务器作为网关或者代理时,为了完成请求访问下一个服务器,但该服务器返回了非法的应答。
503: ('service_unavailable', 'unavailable') # 服务器由于维护或者负载过重未能应答
504: ('gateway_timeout') # 由作为代理或网关的服务器使用,表示不能及时地从远程服务器获得应答
505: ('http_version_not_supported', 'http_version') # 服务器不支持请求中所指明的HTTP版本
506: ('variant_also_negotiates')
507: ('insufficient_storage')
509: ('bandwidth_limit_exceeded', 'bandwidth')
510: ('not_extended')
511: ('network_authentication_required', 'network_auth', 'network_authentication')
状态码 | 含义 |
100~199 | 连接继续 |
200~299 | 各种成功的请求 |
300~399 | 重定向 |
400~499 | 客户端错误 |
500~599 | 服务端错误 |
三、高级操作
http/https 协议是一种无状态的协议,对事物处理无记忆功能,所以每次请求都是一个独立状态
- 比如你访问不同的页面是不同的几次请求;还有一些要登录之后才能爬取,而登录前后的cookie不同
会话维持作用:跨请求时保持住某些参数
为解决无状态协议,就有了 cookie 和 session 的出现
1、模拟登录
1,在requests中,如果直接利用 get()或者 post()等方法的确可以做到模拟网页的请求,但这实际上是相当于不同的会话,每次请求都是独立的。
当我们向服务器发送请求后,服务器处理请求之后返回结果。这是一个独立的过程,再次向服务器发出请求,服务器做出响应又是一次独立的过程。
不会有一条网线一直连着你的电脑和服务器来完成你的所有请求
2,以上是因为我们访问每一个互联网页面,都是通过 HTTP 协议进行的,HTTP协议是无状态的协议。无状态是指协议对于事务处理没有记忆功能,缺少状态意味着,假如后面的处理需要前面的信息,则前面的信息必须重传,这样可能导致每次连接传送的数据量增大3,建立会话对象让你能够跨请求保持某些参数,比如,仅使用 HTTP 协议的话,我们登录一个网站的时候,假如登录成功了,但是当我们访问该网站的其他网页的时候,该登录状态则会消失,此时还需要再登录一次,只要页面涉及更新,就需要反复的进行登录,这是非常不方便的。
4,所以此时,我们需要将对应的会话信息,比如登录成功等信息通过一些方式保存下来
5,比较常用的方式有两种:通过 Cookie 保存会话信息或通过 Session 保存会话信息
因此为了解决这个问题,就出现了Session 和 Cookies 来保持http连接状态
(1)Cookie维持会话
#* 通过cookie维持的只是一种状态 ==》用户信息(账号+密码)
应用场景:
碰到一定需要登录才可以访问的网站,那爬虫也需要携带上登录后的信息(cookie)好处: 能请求需要登录才可以访问的页面
坏处:会大大提高你被反爬的几率 (换账号)爬虫请求非常快
import requests # 构建身份伪装的时候 字典内是可以放多条信息的
head = {
'cookie': 'UM_distinctid=1837e7ffbf6dda-0360993970b77c-78565470-1fa400-1837e7ffbf7fa1; CNZZDATA1279807957=36991445-1664272379-null%6',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36',
}
response = requests.get("https://www.jianshu.com/",headers = head)
print(response.text)注意:cookie是有有效期的
(2)Session维持会话
# 让服务器知道你还是上一次的你
# 验证码处理
首先创建session对象,通过session对象发请求,作用就是让服务器知道你是上一次的你import requests
sx = requests.session() # 创建一个session对象
sx.get('https://www.baidu.com/') # 通过session对象发请求
response = sx.get('https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=python&fenlei=256&rsv_pq=0xa7948b5d00')
print(response.text)比如说验证码登录验证的时候,画图演示,获取文字,然后识别文字之后再提交文字数据,两次请求,不能刷新。
2、代理设置
想知道本机IP,可以在网站上搜Ip就可以看到
代理 IP 使用
# 目标站点:https://www.baidu.com
url= 'https://www.baidu.com'
# 组建IP信息
p ={
'http':'113.124.86.24:9999',
'https':'113.124.86.24:9999',
}
hc = requests.get(url,proxies =p ) # proxies:携带IP信息
print(hc.status_code)
3、超时设置
# 目标站点 : http://baidu.com
url= 'https://www.baidu.com'
response = requests.get(url,timeout = 0.000000003) # 单位以秒为单位。这个时间内没响应成功,就报错
print(response.status_code)
4、异常处理
url= 'https://www.baidu.com'
try:
r = requests.get(url,timeout = 0.0000000001)
print(r.status_code)
except: # 也可以把报错原因写在后面 ==》except(xxxx):
print('timeout!')