Python-Requests1-批量登录获取uid
需求:从表格取不同的手机号和密码登录,获取不同用户的信息,写入本地表格
requests官网:https://github.com/requests/requests
1、安装Requests模块
1、官网下载requests包
2、解压,命令行进入python目录,运行安装命令
python setup.py install
测试有没有安装成功,如果import没有报错就是安装成功
$cd d:\python
$python
import requests
打开pycharm,导入requests即可
2、request基本使用
- get请求
params = {'key1': 'value1', 'key2': 'value2'}
resp_get = requests.get("url_get", params=params) ```
2. POST请求
设置header、cookies、请求参数
headers = {'Accept-Encoding':'gzip,deflate', ' Accept-Language':'zh-cn'}
params = {'key1': 'value1', 'key2': 'value2'}
cookies = dict(Cookies='g0yk_6c66_think_language=zh-Hans-CN; ekdf_4878119f=a7b06c8ee66940ccdf424170c2cc0e10')
resp_post = requests.post(url_post, headers=headers, data=params, cookies=cookies)```
- 获取响应信息
r = requests.get("url_get", params=params)
r.text # 获取响应内容
r.encoding # 根据http头部返回响应编码
r.status_code # 获取响应状态码
r.headers # 响应头,返回的类型是字典形式,
r.headers['Content-Type'] # http头部大小写不敏感,所以访问响应头字段的时候任意大小写都可以
r.cookies # 获取cookie```
####4. 完成登录接口
//用手机号和密码访问登录接口并返回data;登陆失败则返回0
def userLoginRequest(self,account,password):
requrl = "http://xxx.cn/login.json"
header = {……}
cookies = {……}
params = {'fields':'access_toke}
params['account'] = account #读取手机号
params['password'] = password #读取密码
r = requests.post(requrl,header,cookies,params)
if(str(r.status_code)=='200'): # 请求通过的时候,才提取data
response = json.loads(r.text)
print(response['data'])
if(response['data']):
return response['data']
return 0
自动读取表格的手机号+密码,调用登录接口再提取用户身份id,写入本地表格
coding:utf-8
import xlrd
openPath = u'E:/Automation/appiumCase/xxx/sheet/user.xls'
savePath = u'E:/Automation/appiumCase/xxx/sheet/user2.xls'
excel = xlrd.open_workbook(openPath)
sheet = excel.sheets()[0] # 读取第一个sheet数据
result = ['uid', 'phone', 'password', 'token']
for i in range(1, 200): # 循环次数,取决于表格的数据行数
phone = str(sheet.row_values(i)[1])
password = str(int(sheet.row_values(i)[2]))
resJon = Login().userLoginRequest(phone, password) # 调用登录接口
if (resJon != 0):
result.append(resJon['uid']) # 提取uid
else:
print(str(sheet.row_values(i)[1]) + ' Login error!') # 否则提示登陆失败
ExcelUtil().writeArrayToExcel(result, 3, savePath) # 手机号+密码+uid,写入表格```