网络编程

怎么用python调用一个接口,或者访问一个网站,一个是urllib模块是python自带的标准包,不需要安装可以直接用,还有一个在urllib基础上开发的request模块,是第三方的,需要先安装才可以用,下面详细介绍一下,如何通过这两个模块进行URL请求。

一、urllib模块

1、 urllib中get请求
from urllib.request import urlopen#导入urlopen方法,发送请求时用的
import json #转换返回的数据时用的
url = 'http://python.nnzhp.cn/get_sites'
res = urlopen(url).read().decode() #.read()返回的是bytes类型,加上.decode()返回的结果是字符串形式的json
new_res = json.loads(res)#把返回的json转成python的数据类型(list/dict)
print(new_res)

2、 urllib中post请求
from urllib.request import urlopen #导入urlopen方法,发送请求时用的
from urllib.parse import urlencode#导入urlencode方法,是转换请求数据格式用的
data = {
"username":"hahahahahahah",
"password":"123456",
"c_passwd":"123456"
}
url='http://api.nnzhp.cn//getmoney'
param = urlencode(data).encode() #urlencode是将data里的数据转为'username=hahahahahahah&c_passwd=123456&password=123456'
#encode将字符串转为字节,返回结果是b'username=hahahahahahah&c_passwd=123456&password=123456'
new_res=urlopen(url,param).read().decode() #将url中的内容转存在new_res里面
print(new_res)

注意urllib模块发get和post请求的区别是:都是使用urlopen方法,只是post请求需要将数据加进去
3、 url解码
# unquote就是把url编码变成原来字符串
# quote把特殊字符变成url编码
from urllib.parse import urlencode,quote,quote_plus,unquote,unquote_plus
url='http://python.nnzhp.cn/get_sites:.,''.,'
print(quote(url)) #返回http%3A//python.nnzhp.cn/get_sites%3A.%2C.%2C 有特殊字符变成一个url编码
print(quote_plus(url))#返回http%3A//python.nnzhp.cn/get_sites%3A.%2C.%2C 比quote解析的更强大一点
url2='http%3A//python.nnzhp.cn/get_sites%3A.%2C.%2C '
print(unquote(url2)) #返回结果http://python.nnzhp.cn/get_sites:.,.,
print(unquote_plus(url2)) #比unquote解析的更强大一点


二、requests模块

1、get请求
url='https://www.baidu.com/'
import requests
res01=requests.get(url).text#返回的字符串,主要用于html格式的网站
res02=requests.get(url).json()#这样返回的json的数据类型,它里面有list和字典,如果返回不是json类型,使用这种方法会报错
print(res01)
print(res02)

注意,返回的两种格式.text返回的是字符串,一般请求html的时候,会使用,.json是等请求的接口返回的是json数据类型的时候使用,注意如果请求的url内容不是json类型,是会报错的,常见的json格式
也有list和字典,如下
格式一:列表形式

格式二json串形式

2、 requests中的post请求
# 方式一
import requests
url_reg = 'http://python.nnzhp.cn/reg?username=lhl&password'
'=123456&c_passwd=123456'
res = requests.post(url_reg).json()
print(type(res),res)

# 方式二
import requests
url_set = 'http://python.nnzhp.cn/set_sties'
d = {
"stie":"hahfsdfsdf",
"url":"http://www.nnzhp.cn"
}
res = requests.post(url_set,json=d).json()
print(res)



原文地址:https://www.cnblogs.com/MLing/p/7208586.html