需求:從表格取不同的手機(jī)號(hào)和密碼登錄柔昼,獲取不同用戶的信息旱眯,寫入本地表格
requests官網(wǎng):https://github.com/requests/requests
1、安裝Requests模塊
1寻咒、官網(wǎng)下載requests包
2、解壓,命令行進(jìn)入python目錄匙姜,運(yùn)行安裝命令
python setup.py install
測試有沒有安裝成功,如果import沒有報(bào)錯(cuò)就是安裝成功
$cd d:\python
$python
import requests
打開pycharm,導(dǎo)入requests即可
2冯痢、request基本使用
- get請(qǐng)求
params = {'key1': 'value1', 'key2': 'value2'}
resp_get = requests.get("url_get", params=params)
- POST請(qǐng)求
設(shè)置header氮昧、cookies、請(qǐng)求參數(shù)
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)
- 獲取響應(yīng)信息
r = requests.get("url_get", params=params)
r.text # 獲取響應(yīng)內(nèi)容
r.encoding # 根據(jù)http頭部返回響應(yīng)編碼
r.status_code # 獲取響應(yīng)狀態(tài)碼
r.headers # 響應(yīng)頭浦楣,返回的類型是字典形式,
r.headers['Content-Type'] # http頭部大小寫不敏感袖肥,所以訪問響應(yīng)頭字段的時(shí)候任意大小寫都可以
r.cookies # 獲取cookie
4. 完成登錄接口
//用手機(jī)號(hào)和密碼訪問登錄接口并返回data;登陸失敗則返回0
def userLoginRequest(self,account,password):
requrl = "http://xxx.cn/login.json"
header = {……}
cookies = {……}
params = {'fields':'access_toke}
params['account'] = account #讀取手機(jī)號(hào)
params['password'] = password #讀取密碼
r = requests.post(requrl,header,cookies,params)
if(str(r.status_code)=='200'): # 請(qǐng)求通過的時(shí)候振劳,才提取data
response = json.loads(r.text)
print(response['data'])
if(response['data']):
return response['data']
return 0
自動(dòng)讀取表格的手機(jī)號(hào)+密碼椎组,調(diào)用登錄接口再提取用戶身份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] # 讀取第一個(gè)sheet數(shù)據(jù)
result = ['uid', 'phone', 'password', 'token']
for i in range(1, 200): # 循環(huán)次數(shù),取決于表格的數(shù)據(jù)行數(shù)
phone = str(sheet.row_values(i)[1])
password = str(int(sheet.row_values(i)[2]))
resJon = Login().userLoginRequest(phone, password) # 調(diào)用登錄接口
if (resJon != 0):
result.append(resJon['uid']) # 提取uid
else:
print(str(sheet.row_values(i)[1]) + ' Login error!') # 否則提示登陸失敗
ExcelUtil().writeArrayToExcel(result, 3, savePath) # 手機(jī)號(hào)+密碼+uid历恐,寫入表格