Requests 是第三方模块,如果要使用的话需要导入。Requests也可以说是urllib模块的升级版,使用上更方便。
这是使用urllib的例子。
importurllib.requestimportjson
url= ‘http://www.weather.com.cn/data/sk/101190408.html‘res= urllib.request.urlopen(url)#发送请求
result = res.read().decode()#获取结果,结果是byte类型的需要decode()
print(json.loads(result))
下面是Requests 模块的使用。
支持的请求:
requests.get(‘https://github.com/timeline.json’) #GET请求
requests.post(“http:xxx.xx.com/post”) #POST请求
requests.put(“http:xxx.xx.com/put”) #PUT请求
requests.delete(“http:xxx.xx.com/delete”) #DELETE请求
requests.head(“http:xxx.xx.com/head”) #HEAD请求
requests.options(“http:xxx.xx.com/get”) #OPTIONS请求
发送GET请求:
importrequests,json
url= ‘http://api.xx.cn/api/user/stu_info?stu_name=hi‘req= requests.get(url)#发送get请求
print(req.text)#获取结果直接返回的就是json串
print(type(req.text)) #str
print(json.loads(req.text))#json转字典
print(req.json())#获取结果就是字典,只有返回的是json串的话才能用req.json()
print(type(req.json()))#dict
发送POST请求
url = ‘http://api.xxx.cn/api/user/login‘data= {‘username‘:‘aa‘,‘passwd‘:‘123‘}
req= requests.post(url,data)#发送post请求,第一个参数是url,第二个参数是请求的数据
print(req.json())
发送格式为json的数据
url = ‘http://api.xxx.cn/api/user/add_stu‘data={"name":"aa","grade":"bb","phone":13512530000,
}
req= requests.post(url,json=data)#发送post请求,第一个参数是url,第二个参数是请求的数据,发送的json的话就写json=data
print(req.json())
发送带cookie的请求
url = ‘http://api.xx.cn/api/user/gold_add‘data= {‘stu_id‘:231,‘gold‘:‘100‘}
cookie= {‘aa‘:‘3d867b361afdaac1381b02ae746c7278‘}#key 为登陆的用户名,value为sign的值
req = requests.post(url,data,cookies=cookie)#添加cookie
print(req.json())
发送的请求中带Header
url = ‘http://api.xxx.cn/api/user/all_stu‘header= {‘User-Agent‘:‘Chrome‘}
req= requests.get(url,headers =header)print(req.json())
上传文件
url = ‘http://api.xxx.cn/api/file/file_upload‘f= open(r‘D:\aa.jpg‘,‘rb‘)#图片要指定以二进制方式打开
r =requests.post(url,files={‘file‘:f})print(r.json())
下载文件,图片,视频
url = ‘https://images2017.cnblogs.com/blog/412654/201712/412654-20171213115213238-464712233.png‘r=requests.get(url)print(r.status_code)#获取请求状态码
print(r.content)#获取返回结果二进制格式的
fw = open(‘bt.jpg‘,‘wb‘)#当前路径#fw = open(r‘d:\bt.jpg‘,‘wb‘)#指定绝对路径
fw.write(r.content)#将二进制格式内容写入文件
fw.close()
爬虫,把网页保存到本地
url = ‘http://www.cnblogs.com/nancyzhu/p/8029994.html‘r=requests.get(url)
f= open(‘page.html‘,‘wb‘)
f.write(r.content)
f.close()