需求:從表格取不同的手機號和密碼登錄,獲取不同用戶的信息,寫入本地表格
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)
- 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,寫入表格