urllib库发送get和post请求

urllib是Python中内置的发送网络请求的一个库(包),在Python2中由urllib和urllib2两个库来实现请求的发送,可是在Python中已经不存在urllib2这个库了,已经将urllib和urllib2合并为urllib。
urllib是一个库(包),request是urllib库里面用于发送网络请求的一个模块
json

1.发送一个不携带参数的get请求api

 

import urllib.request
#发起一个不携带参数的get请求
response=urllib.request.urlopen('http://www.baidu.com')
print(response.reason)
#调用status属性能够这次请求响应的状态码,200表示这次请求成功
print(response.status)
#调用url属性,能够获取这次请求的地址
print(response.url)
print(response.headers)
#因为使用read方法拿到的响应的数据是二进制数据,全部须要使用decode解码成utf-8编码
# print(response.read().decode('utf-8'))

 

2.发送一个携带参数的get请求网络

import urllib.request
import urllib.parse
#http://www.yundama.com/index/login?username=1313131&password=132213213&utype=1&vcode=2132312

# 定义出基础网址
base_url='http://www.yundama.com/index/login'
#构造一个字典参数
data_dict={
    "username":"1313131",
    "password":"13221321",
    "utype":"1",
    "vcode":"2132312"
}
# 使用urlencode这个方法将字典序列化成字符串,最后和基础网址进行拼接
data_string=urllib.parse.urlencode(data_dict)
print(data_string)
new_url=base_url+"?"+data_string
response=urllib.request.urlopen(new_url)
print(response.read().decode('utf-8'))

3.构造一个携带参数的POST请求函数

import urllib.request
import urllib.parse
#测试网址:http://httpbin.org/post

#定义一个字典参数
data_dict={"username":"zhangsan","password":"123456"}
#使用urlencode将字典参数序列化成字符串
data_string=urllib.parse.urlencode(data_dict)
#将序列化后的字符串转换成二进制数据,由于post请求携带的是二进制参数
last_data=bytes(data_string,encoding='utf-8')
#若是给urlopen这个函数传递了data这个参数,那么它的请求方式则不是get请求,而是post请求
response=urllib.request.urlopen("http://httpbin.org/post",data=last_data)
#咱们的参数出如今form表单中,这代表是模拟了表单的提交方式,以post方式传输数据
print(response.read().decode('utf-8'))

 

4.补充:post

若是直接将中文传入URL中请求,会致使编码错误。咱们须要使用quote() ,对该中文关键字进行URL编码测试

 

import urllib.request
city=urllib.request.quote('郑州市'.encode('utf-8'))
response=urllib.request.urlopen('http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'.format(city))
print(response.read().decode('utf-8'))
相关文章
相关标签/搜索