Requests使用

Requests

简介

Requests库

img

requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到。可以说,**Requests 完全满足如今网络的需求

开源地址:https://github.com/kennethreitz/requests
中文文档:http://docs.python-requests.org/zh_CN/latest/index.html

一、Requests基础

1.安装requests库

pip3 install requests

2.使用Requests库

import requests

二 、发送请求与接收响应(基于GET请求)

1.传送pramas参数

  • 参数包含在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
  • 通过get方法传送参数
data = {
        "name": "zhangsan",
        "age": 30
    }
response = requests.get("http://httpbin.org/get", params=data)
print(response.text)

2.模拟发送请求头(传送headers参数)

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)

三、发送请求与接收响应(基于post请求)

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)

四、Request属性

属性 描述
response.text 获取str类型(Unicode编码)的响应
response.content 获取bytes类型的响应
response.status_code 获取响应状态码
response.headers 获取响应头
response.request 获取响应对应的请求

五、代理

猜你喜欢

转载自www.cnblogs.com/jiangchunsheng/p/12093031.html
今日推荐