文章标题

来源:互联网 发布:速学英语软件 编辑:程序博客网 时间:2024/06/05 15:29

requests 库是用Python语言编写,基于 urllib,但它的API比 urllib 更加好用,更加方便,可以节约我们大量的工作。
安装requests

pip install requests

使用requests

import requests>>>r=requests.get('http://www.baidu.com')  #发起GET请求>>>r.status_code)                    #查看响应状态码200>>>r.encoding 'ISO-8859-1'>>>r.apparent_encoding              'utf-8'>>>r.url                           #返回请求的url'http://www.baidu.com/'>>>r.text                          #返回响应数据>>>r.content                       #返回响应的二进制数据>>>r.reason                        #返回原因短语'OK'

r.encoding 是从响应charset首部中解析的响应内容编码方式,如果响应中没有charset首部则默认为ISO-8859-1,r.apparent_encoding是响应的实际编码方式

requests.get(url,**kwargs)方法的参数:

  • url即是要请求的URL
  • **kwargs代表
  • params:作为参数增加到url中
>>>>>> r = requests.get(url='http://dict.baidu.com/s', params={'wd':'python'})>>>r.url'http://dict.baidu.com/s?wd=python'

timeout : 设定超时时间
设置和服务器建立连接的超时时间,和服务器返回数据的时间没有关系

r = requests.get(url='http://dict.baidu.com', timeout=10)

headers : HTTP首部字段,参数为字典

headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1'}>>>r = requests.get(url='http://dict.baidu.com', headers=headers)

更改user-agent首部,可以将请求伪装成浏览器
proxies : 设定代理服务器

proxy={'http':'180.168.179.193:8080'}

verify:验证证书,默认为True

原创粉丝点击