python第三方库requests简单介绍
Posted Eric_nan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python第三方库requests简单介绍相关的知识,希望对你有一定的参考价值。
一、发送请求与传递参数
简单demo:
import requests r = requests.get(url=\'http://www.itwhy.org\') # 最基本的GET请求 print(r.status_code) # 获取返回状态 r = requests.get(url=\'http://dict.baidu.com/s\', params={\'wd\':\'python\'}) #带参数的GET请求 print(r.url) print(r.text) #打印解码后的返回数据
1、带参数的请求
import requests requests.get(\'http://www.dict.baidu.com/s\', params={\'wd\': \'python\'}) #GET参数实例 requests.post(\'http://www.itwhy.org/wp-comments-post.php\', data={\'comment\': \'测试POST\'}) #POST参数实例
2、post发送json数据:
import requests import json r = requests.post(\'https://api.github.com/some/endpoint\', data=json.dumps({\'some\': \'data\'})) print(r.json())
3、定制header:
import requests import json data = {\'some\': \'data\'} headers = {\'content-type\': \'application/json\', \'User-Agent\': \'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0\'} r = requests.post(\'https://api.github.com/some/endpoint\', data=data, headers=headers) print(r.text)
二、response对象
使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,如上实例中已经提到的 r.text、r.status_code……
获取文本方式的响应体实例:当你访问 r.text 之时,会使用其响应的文本编码进行解码,并且你可以修改其编码让 r.text 使用自定义的编码进行解码
响应:
r.status_code #响应状态码 r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取 r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩 r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码 r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None #*特殊方法*# r.json() #Requests中内置的JSON解码器 r.raise_for_status() #失败请求(非200响应)抛出异常
demo:
import requests URL = \'http://ip.taobao.com/service/getIpInfo.php\' # 淘宝IP地址库API try: r = requests.get(URL, params={\'ip\': \'8.8.8.8\'}, timeout=1) r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常 except requests.RequestException as e: print(e) else: result = r.json() print(type(result), result, sep=\'\\n\') # 结果: # <class \'dict\'> # {\'code\': 0, \'data\': {\'ip\': \'8.8.8.8\', \'country\': \'美国\', \'area\': \'\', \'region\': \'XX\', \'city\': \'XX\', \'county\': \'XX\', \'isp\': \'Level3\', \'country_id\': \'US\', \'area_id\': \'\', \'region_id\': \'xx\', \'city_id\': \'xx\', \'county_id\': \'xx\', \'isp_id\': \'200053\'}}
三、上传文件
1、上传文件
import requests url = \'http://127.0.0.1:5000/upload\' files = {\'file\': open(\'/home/lyb/sjzl.mpg\', \'rb\')} #files = {\'file\': (\'report.jpg\', open(\'/home/lyb/sjzl.mpg\', \'rb\'))} #显式的设置文件名 r = requests.post(url, files=files) print(r.text)
2、可以把字符串当着文件进行上传:
import requests url = \'http://127.0.0.1:5000/upload\' files = {\'file\': (\'test.txt\', b\'Hello Requests.\')} #必需显式的设置文件名 r = requests.post(url, files=files) print(r.text)
四、身份验证
1、基本身份认证(HTTP Basic Auth):
import requests from requests.auth import HTTPBasicAuth r = requests.get(\'https://httpbin.org/hidden-basic-auth/user/passwd\', auth=HTTPBasicAuth(\'user\', \'passwd\')) # r = requests.get(\'https://httpbin.org/hidden-basic-auth/user/passwd\', auth=(\'user\', \'passwd\')) # 简写 print(r.json())
2、非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的:
requests.get(URL, auth=HTTPDigestAuth(\'user\', \'pass\'))
五、Cookies与会话对象
1、如果某个响应中包含一些Cookie,你可以快速访问它们:
import requests r = requests.get(\'http://www.google.com.hk/\') print(r.cookies[\'NID\']) print(tuple(r.cookies))
2、要想发送你的cookies到服务器,可以使用 cookies 参数:
import requests url = \'http://httpbin.org/cookies\' cookies = {\'testCookies_1\': \'Hello_Python3\', \'testCookies_2\': \'Hello_Requests\'} # 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。 r = requests.get(url, cookies=cookies) print(r.json())
六、超时与异常
timeout 仅对连接过程有效,与响应体的下载无关。
>>> requests.get(\'http://github.com\', timeout=0.001) Traceback (most recent call last): File "<stdin>", line 1, in <module> requests.exceptions.Timeout: HTTPConnectionPool(host=\'github.com\', port=80): Request timed out. (timeout=0.001)
七、实例demo
1、使用python第三方库requests,结合unittest、ddt数据驱动,实现get请求:使用多个搜索词,实现多条搜索case用例测试
import requests import unittest import ddt @ddt.ddt class testClass(unittest.TestCase): @ddt.data("App专项测试", "自动化", "Python") def testGet(self, queryword): #header部分的配置 headers_data = { \'User-Agent\':\'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36\', \'Host\':\'m.imooc.com\', \'Referer\': \'https://m.imooc.com/\', \'Connection\':\'keep-alive\', # 持续连接 \'Accept-Encoding\':\'gzip, deflate, br\' } #cookies部分的配置 cookies_data = dict(imooc_uuid=\'f7356a8d-3dda-48b4-9a33-127b8f57e1db\', imooc_isnew_ct=\'1522158893\', imooc_isnew=\'2\', page = \'https://m.imooc.com/\') #get请求的构造 res = requests.get( "https://m.imooc.com/search/?words="+queryword, headers=headers_data, cookies=cookies_data) #print res.status_code #print res.text self.assertTrue("共找到" in res.text) if __name__ == "__main__": unittest.main()
2、使用python第三方库requests,结合unittest、ddt数据驱动,实现post请求:使用多个账户密码,实现多个用户登录测试
import requests import unittest import ddt @ddt.ddt class testClass(unittest.TestCase): @ddt.data( ("15977778888", "999999"), ("15977778889", "999998") ) @ddt.unpack # 数据是元组或列表等格式,需要经过unpack解包后,再用于驱动实例 def testPost(self, username_data, password_data): formdata = { "username": username_data, "password": password_data, "verify": \'\', "referer":\'https://m.imooc.com\'} headers_data = { \'User-Agent\': \'Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36\', \'Host\': \'m.imooc.com\' } #cookies部分的配置 cookies_data = dict(imooc_uuid=\'ffbd103a-b800-4170-a267-4ea3b301ff06\', imooc_isnew_ct=\'1511175583\', imooc_isnew=\'2\', page = \'https://m.imooc.com/\') res = requests.post("https://m.imooc.com/passport/user/login", data = formdata, headers = headers_data, cookies = cookies_data ) print(res.json()) # res是json_str格式,res.json():转化成字典格式 print(type(res.json())) self.assertTrue(90003 == res.json()[\'status\'] or 10005 == res.json()[\'status\']) # 判断状态码是否是90003或10005 if __name__ == "__main__": unittest.main()
运行结果:
G:\\Python\\selenium_test\\Scripts\\python.exe G:/Python/selenium_test/ddt_case/selenium_test.py .{\'status\': 90003, \'msg\': \'验证码为空\', \'data\': []} <class \'dict\'> {\'status\': 90003, \'msg\': \'验证码为空\', \'data\': []} <class \'dict\'> . ---------------------------------------------------------------------- Ran 2 tests in 1.057s OK
备注:本文采集于:https://www.cnblogs.com/mrchige/p/6409444.html ,仅用于记录笔记学习!
以上是关于python第三方库requests简单介绍的主要内容,如果未能解决你的问题,请参考以下文章