Python Request库学习(一),,一、安装Reques


一、安装Requests库

pip install requests

二、Request库基本使用

  在Request库中常见的两种方法就是GET方法和Post方法,安装成功后,可以看到它自带了两个示例:

技术图片

技术图片

此外还支持De‘lete、Put、Options方法。而equests库的方便之处在于所有的请求都可以使用一句代码来实现。

三、Get方法

使用Get:

技术图片

简单示例:

技术图片运行结果:

技术图片

Params:

Get方法常见的形式:https://ip:port/xxxx?xx=xx,如果访问带有参数的Url,可以传入一个Dict。

param={‘name‘:‘aaaa‘,‘age‘:20}res=requests.get(‘http://192.168.114.130/get.php‘,params=param) print(res.text)输出结果就是上面传入的参数。Header:也是传入一个Dict作为参数:header={‘User-Agent‘:‘Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/77.0.3865.90Safari/537.36‘}res=requests.get(‘http://192.168.114.130/get.php‘,params=param,headers=header)抓取图片:  以xampp的图标为例: importrequests
defhtml():res=requests.get(‘http://192.168.114.130/favicon.ico‘)ifres.status_code==200:print(res.content)withopen(‘favicon.ico‘,‘wb‘)asf:f.write(res.content)else:print(res.status_code)html()res.content返回的是二进制数据,直接保存的话会报TypeError: write() argument must be str, not bytes,所以想将图片保存在本地需要以二进制的方式打开。timeout超时设置,有时爬取网页一直卡在等待页面,没有报错也没有相应,所以需要设置一个超时设置。超出设定时间后没有相应,则会抛出异常。res=requests.get(‘http://python-requests.org‘,timeout=1)输出:

requests.exceptions.ReadTimeout: HTTPSConnectionPool(host=‘requests.kennethreitz.org‘, port=443): Read timed out. (read timeout=1)

相应

其他属性和方法等:

  print(res.ok,type(res.ok))print(res.cookies,type(res.cookies))print(res.headers,type(res.headers))print(res.url,type(res.url))print(res.history,type(res.history))输出:技术图片

Python Request库学习(一)

评论关闭