Requests to use

Requests

Brief introduction

Requests Library

img

requestsIt is a very useful Python HTTP client library, often used when writing reptiles and test server response data. It can be said, ** Requests to fully meet the needs of today's network

Open Source Address: https://github.com/kennethreitz/requests
Chinese document: http://docs.python-requests.org/zh_CN/latest/index.html

A, Requests basis

1. Install requests library

pip3 install requests

2. Requests Library

import requests

Second, in response to receiving the transmission request (GET request based)

1. The transmission parameters pramas

  • Parameters contained in the url
response = requests.get("http://httpbin.org/get?name=春生&age=22")
print(response.text)
httpbin.org 这个网站能测试 HTTP 请求和响应的各种信息,比如 cookie、ip、headers 和登录验证等,且支持 GET、POST 等多种方法,对 web 开发和测试很有帮助。

它用 Python + Flask 编写,是一个开源项目。

官方网站:http://httpbin.org/
开源地址:https://github.com/Runscope/httpbin
  • Transmission parameters get method
data = {
        "name": "zhangsan",
        "age": 30
    }
response = requests.get("http://httpbin.org/get", params=data)
print(response.text)

2. Analog transmission request header (transport headers parameter)

import requests

headers = {

    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
}

url = "http://httpbin.org/get"

response = requests.get(url=url,headers=headers)

print(response.text)

Third, the transmission request and reception response (based on a post request)

import requests

headers = {

    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
}

url = "http://httpbin.org/post"

data ={
    "cnbool": "PythonAV",
    "name": "chunsheng",
    "age": "18"
}

response = requests.post(url=url,data=data,headers=headers)

print(response.text)

Four, Request Properties

Attributes description
response.text Types Get str (Unicode encoded) response
response.content Get the type of response bytes
response.status_code Get the response status code
response.headers Get response header
response.request Fetch response corresponding request

5, agents

Guess you like

Origin www.cnblogs.com/jiangchunsheng/p/12093031.html