当前位置:网站首页>请求模块(requests)

请求模块(requests)

2022-07-01 06:17:00 HHYZBC

requests模块是python中常用的发送请求模块,作用是发送http请求,获取响应数据。使用前需要使用pip进行下载。

pip install requests

使用requests

  • 使用requests发送get请求
requests.get('https://www.douban.com/')
  • 发送带有参数的get请求

传入一个字典作为params参数即可

requests.get('https://www.douban.com/',params={'a':'python','b':'100'})

实例请求的url则为:

https://www.douban.com/search?a=python&b=100'
  • 发送需要传入HTTP Header的get请求

传入一个字段作为headers参数即可

requests.get('https://www.douban.com/', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'})
  • 发送json数据的get请求:

传入一个字典作为json参数即可

params = {'key': 'value'}
requests.post(url, json=params)
  • 发送文件的get请求

传入一个字典作为files参数即可,字典的值为传入的文件,读取文件时需要使用rb模式二进制进行读取。

upload_files = {'file': open('report.xls', 'rb')}
requests.post(url, files=upload_files)
  • 发送带有Cookie的get请求

传入一个字典作为cookies参数即可。

cookies= {'name': 'hhh', 'pwd': 'working'}
requests.get(url, cookies=cookies)
  • 指定超时时间的get请求

传入一个数字作为timeout参数即可。注意timeout参数的单位是秒

requests.get(url, timeout=3)
  • 发送post请求

将get()方法改成post()方法即可。如何传入一个字典作为data参数,表示作为post请求的数据。

requests.post('https://accounts.douban.com/login', data={'form_email': '[email protected]'})

如果需要使用其他请求方法时,则将post()方法换成响应的方法即可。如put(),delete()等,就可以使用put或者delete方式请求数据了。

响应内容常用方法

使用上面方法后,都会返回一个对象,包含着所有响应内容。一般使用response进行接收,表示响应内容。该对象常用的属性有:

  • status_code
    • 状态码
  • text
    • 响应体
  • content
    • 也是响应体,但是无论响应是文本还是二进制内容,content属性获得都是bytes对象
    • 可以在该属性后面再使用decode方法,对数据进行解码操作,默认是utf-8
  • encoding
    • 查看编码格式
  • json
    • 获取json数据
  • headers
    • 获取响应头
  • Cookie
    • 获取Cookie

原网站

版权声明
本文为[HHYZBC]所创,转载请带上原文链接,感谢
https://blog.csdn.net/HHYZBC/article/details/125385170