测开-requests框架(Python)

requests框架参考链接:

参考1:https://requests.readthedocs.io/zh_CN/latest/user/quickstart.html
参考2:https://blog.csdn.net/byweiker/article/details/79234853
参考3:https://www.cnblogs.com/wxlog/p/10731540.html
中文api文档:https://requests.readthedocs.io/zh_CN/latest/

框架特点:

  • 功能全面:http/https全面支持;
  • 使用简单:简单易用,不用担心底层细节;
  • 定制性高:借助于hook机制完成通用处理;

演练环境:http://httpbin.testing-studio.com

Request方法

requests.request(method, url, **kwargs)

**kwargs:控制访问的参数,均为可选项,共13个

  • 1)params:字典或字节序列,作为参数增加到url中

  • 2)  data:字典、字节序列或文件对象,作为Request的对象

  • 3)json:JSON格式的数据,作为Request的内容
    • requests没有提供对xml封装的接口,所有使用data(文本)来发送数据,同时需要修改headers中的Content-Type
    • "Content-Type": "application/xml"

  • 4)headers:字典,HTTP定制头

  • 8)timeout:设定超时时间,秒为单位

  • 9)proxies:字典类型,设置访问代理服务器,可以增加登录认证

  • 10)allow_redirects:True/False,默认为Ture,重定向开关
  • 11)stream:True/False,默认为True,获取内容立即下载开关
  • 12)verigy:True/False,默认为True,认证SSL证书开关
  • 13)cert:本地SSL证书路径

一、请求方式

1.get请求传递参数:params=

p={"name":"john","age":17}
response=requests.get("http://localhost:5000/get_params",params=p)
print(response.text)
print(response.url)
##输出
{"name": "john", "age": "17"}
http://localhost:5000/get_params?name=john&age=17
说明:
这里做了三件事,先定义一个参数字典p,然后将参数字典以params参数传递给get方法,最后将响应信息打印出来,从响应信息可以看到参数被正确得传递进去,requests帮我们把参数组合到了url里面。

2.post请求传递参数:

  post传递参数和get有所不同,根据服务端取值方式进行不同方式得传递。

  • 传递json格式的参数:json=
p={"name":"john","age":17}
response=requests.post("http://localhost:5000/post_params",json=p)
print(response.text)
###输出:
{"name": "john", "age": 17}
  • 以html中form的形式传递参数:data=
p={"name":"john","age":17}
response=requests.post("http://localhost:5000/post_params",data=p)
print(response.text)
  • 如果form传递得是json格式的参数:data=json.dumps(p)

  说明:
  需要将字典形式的参数转换为json格式,再进行传递。

import json

p={"name":"john","age":17}
response=requests.post("http://localhost:5000/post_params",data=json.dumps(p))
print(response.text)

二、添加headers:headers=

  有些网站访问时必须带有浏览器等信息,如果不传入headers就会报错,如下:

import requests
 
response = requests.get("https://www.zhihu.com/explore")
print(response.text)

返回值:

<html><body><h1>500 Server Error</h1>
An internal server error occured.
</body></html>

当传入headers时:

import requests
 
headers = {
 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
}
response = requests.get("https://www.zhihu.com/explore", headers=headers)
print(response.text)

三、响应response属性

import requests
 
response = requests.get('http://www.jianshu.com')
print(type(response.status_code), response.status_code)
print(type(response.headers), response.headers)
print(type(response.cookies), response.cookies)
print(type(response.url), response.url)
print(type(response.history), response.history)

返回:

<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'Date': 'Thu, 01 Feb 2018 20:47:08 GMT', 'Server': 'Tengine', 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'ETag': 'W/"9f70e869e7cce214b6e9d90f4ceaa53d"', 'Cache-Control': 'max-age=0, private, must-revalidate', 'Set-Cookie': 'locale=zh-CN; path=/', 'X-Request-Id': '366f4cba-8414-4841-bfe2-792aeb8cf302', 'X-Runtime': '0.008350', 'Content-Encoding': 'gzip', 'X-Via': '1.1 gjf22:8 (Cdn Cache Server V2.0), 1.1 PSzqstdx2ps251:10 (Cdn Cache Server V2.0)', 'Connection': 'keep-alive'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie locale=zh-CN for www.jianshu.com/>]>
<class 'str'> https://www.jianshu.com/
<class 'list'> [<Response [301]>]

四、文件上传:files=

import requests
 
files = {'file': open('cookie.txt', 'rb')}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)

五、cookie操作

  • 获取cookies:当需要cookie时,直接调用response.cookies:(response为请求后的返回值);
import requests
 
response = requests.get("https://www.baidu.com")
print(response.cookies)
for key, value in response.cookies.items():
 print(key + '=' + value)
  • 发送cookies到服务器:这是请求关键字cookies=
    def test_cookies2(self):
        url = 'http://httpbin.testing-studio.com/cookies'
        headers = {'User-Agent':'echo'}
        cookies = {'cookie1':'echo1','cookies2':'echo2'}
        r = requests.get(url=url,headers = headers,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())
  • 发送Cookie到服务器:这是headers中的Cookie字段,注意没有s和C大写

    def test_cookies(self):
        url = 'http://httpbin.testing-studio.com/cookies'
        headers = {'Cookie':'echo'}
        r = requests.get(url=url,headers = headers)

 

六、证书验证:verify=False

  因为12306有一个错误证书,我们那它的网站做测试会出现下面的情况,证书不是官方证书,浏览器会识别出一个错误;

import requests
 
response = requests.get('https://www.12306.cn')
print(response.status_code)

返回:
。
。

  正常进入这样的网站,代码如下:

import requests
from requests.packages import urllib3
urllib3.disable_warnings()
response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)

七、代理设置:proxies=

  在进行爬虫爬取时,有时候爬虫会被服务器给屏蔽掉,这时采用的方法主要有降低访问时间,通过代理ip访问,如下:

import requests
 
proxies = {
 "http": "http://127.0.0.1:9743",
 "https": "https://127.0.0.1:9743",
}
 
response = requests.get("https://www.taobao.com", proxies=proxies)
print(response.status_code)

ip可以从网上抓取,或者某宝购买;

如果代理需要设置账户名和密码,只需要将字典更改为如下:
proxies = {
"http":"http://user:password@127.0.0.1:9999"
}
如果你的代理是通过sokces这种方式则需要pip install "requests[socks]"
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}

八、超时设置:timeout =

  访问有些网站时可能会超时,这时设置好timeout就可以解决这个问题;

import requests
from requests.exceptions import ReadTimeout
try:
 response = requests.get("http://httpbin.org/get", timeout = 0.5)
 print(response.status_code)
except ReadTimeout:
 print('Timeout')

九、认证设置:auth=

import requests
from requests.auth import HTTPBasicAuth

class TestHog1:
    def test_auth(self):
        r = requests.get('http://httpbin.testing-studio.com/basic-auth/echo/1234',auth=HTTPBasicAuth('echo','1234'))
        print(r.status_code)

 

十、异常处理

遇到网络问题(如:DNS查询失败、拒绝连接等)时,Requests会抛出一个ConnectionError 异常。

遇到罕见的无效HTTP响应时,Requests则会抛出一个 HTTPError 异常。

若请求超时,则抛出一个 Timeout 异常。

若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。

十一、复杂数据解析

  • mustache:pystache

十二、结构化响应断言json、xml

  • jsonpath
import requests
from jsonpath import jsonpath

class TestHog1:
    def test_hog_json(self):
        r = requests.get('https://ceshiren.com/categories.json')
        utils.print_json(r)
        assert r.json()['category_list']['categories'][1]['name'] == '开源项目'
        assert jsonpath(r.json(),'$..name')[1] == '开源项目'
  • XMLSession

十三、断言体系

  • hamcrest断言体系:PyHamcrest--官网hamcrest.org

from requests_demo0730 import utils
from hamcrest import *

class TestHog1:
    def test_hamcrest(self):
        r = requests.get('https://ceshiren.com/categories.json')
        utils.print_json(r)
        assert_that(r.json()['category_list']['categories'][1]['name'],equal_to('开源项目'))
        assert_that(jsonpath(r.json(), '$..name')[1],equal_to('开源项目'))
  • schema校验:jsonschema--官网json-schema.org,校验地址:jsonschema.net/home

posted on 2020-08-04 13:47  echooche  阅读(61)  评论(0)    收藏  举报

导航