使用 urllib.request 來訪問蘑菇丁、登入
阿新 • • 發佈:2020-08-10
import ssl
import json
#使用urllib 去訪問頁面
import urllib.request as ur
#規避警告
context = ssl._create_unverified_context()
# 登入函式
def Login(info_data):
# 把字典info_data轉成字串、再用過encoding指定的編碼格式編碼字串
test_data = json.dumps(info_data).encode()
print("*******",test_data,"-----",type(test_data))
request_data = ur.Request(#要登入的網址
url='https://api.moguding.net:9000/session/user/v1/login',
# login_data =是{'loginType': 'iphone', 'password': 'hope2019', 'phone': '18681989609'}
#登入頭中的資料
data=json.dumps(info_data).encode(),
#高速伺服器自己是誰, 這裡說自己是app
headers={'Content-Type': 'application/json; charset=UTF-8'})
print(ur.Request)
try:
#實現登入 其中.read()是拿到內容, ,decode是以Python decode() 方法以 encoding 指定的編碼格式解碼字串
response = json.loads(ur.urlopen(request_data, context=context).read().decode())
token = response['data']['token']
#拿到token
if token:
return {
'code': '200','info': '登入成功',
'token': token
}
except Exception as e:
if str(e) == '<urlopen error Remote end closed connection without response>':
return {
'code': '404',
'info': '網路連結超時'
}
else:
return {
'code': '505',
'info': '賬號或密碼錯誤'
}
#獲取學生日報(day)、週報(week)、月報(month)列表
def GetReports(token, reportType):
ids = []
day = {"currPage": 1, "pageSize": 25, "batchId": "", "classId": "",
"teaId": "", "reportType": reportType, "planId": "", "state": 0}
request_data = ur.Request(
#個人中心的網址
url = "https://api.moguding.net:9000/usercenter/user/v1/info",
#url='https://api.moguding.net:9000/practice/paper/v1/list',
headers={
'Authorization': token,
'Content-Type': 'application/json; charset=UTF-8'
},
data=json.dumps(day).encode("utf-8"))
try:
#訪問個人中心、、
response = ur.urlopen(request_data, context=context).read().decode()
#print("response--------------",response)
return response
except Exception as e:
print(e)
if __name__ == '__main__':
response = Login({'loginType': 'iphone', 'password': '密碼', 'phone': '手機號'})
token = response['token']
ids = GetReports(token,"day")
print("個人中心的response: ", ids)