requests库详解

-基础使用注释

import requests
import json

'''
r=requests.get('https://github.com/timeline.json') #创建requests的对象r

#1.发送http请求

r=requests.post('https://github.com/timeline.json') #发送post请求
r=requests.put('https://github.com/timeline.json/put') #发送put请求
r=requests.delete('https://github.com/timeline.json/delete')#发送delete请求
r=requests.head('https://github.com/timeline.json/get') #发送head请求
r=requests.options('https://github.com/timeline.json/get') #发送options请求

#2.为url传递参数

payload={'key1':'value1','key2':'value2'} #字典设置参数
r=requests.get('https://github.com/timeline.json',params=payload) #使用params关键字参数
print(r.url) #打印url,可看到url被正确解码

#3.打印网页内容

r=requests.get('https://blog.csdn.net/iloveyin/article/details/21444613') #获取网页内容
print(r.text) #打印网页内容

#4.改变文本编码

r=requests.get('https://blog.csdn.net/iloveyin/article/details/21444613')
print(r.encoding)# 查看原网页内容编码格式

r.encoding='ISO-8859-1' #改变文本编码格式
print(r.encoding) #查看改变后的文本编码格式
print(r.text) #打印网页内容,此时文本编码格式为ISO-8859-1

#4.json响应内容,requests内置的json解码器,处理json数据

r=requests.get('https://github.com/timeline.json')
print(r.json())

#5.原始响应内容,r.raw访问,设置stream=True

r = requests.get('https://github.com/timeline.json', stream=True) #初始请求设置stream=True
print(r.raw.read(100)) #打印内容的前100个字符

'''
posted @ 2018-08-25 00:00  FortuneFramework  阅读(156)  评论(0编辑  收藏  举报