Skip to content

Instantly share code, notes, and snippets.

@ReinforceZwei
Created December 23, 2021 10:59
Show Gist options
  • Save ReinforceZwei/1d00c5054cc8e49031fa0dde30a47e96 to your computer and use it in GitHub Desktop.
Save ReinforceZwei/1d00c5054cc8e49031fa0dde30a47e96 to your computer and use it in GitHub Desktop.
查詢SunMobile手機號碼數據用量
beautifulsoup4
requests
import requests
import time
from bs4 import BeautifulSoup
LOGIN_URL = "https://www.sunmobile.com.hk/cs/topup/login"
DATA_USAGE_URL = "https://www.sunmobile.com.hk/cs/topup/value_add_servicePlan?datatime{}&mylocale=ch"
class SunMobile:
@staticmethod
def login(number, password):
"""Login to sunmobile. Return session ID. Raise exception if error"""
post_data = {
"pin": number,
"pwd": password,
"lang": "CHN",
"mylocale": ""
}
login_resp = requests.post(LOGIN_URL, post_data)
if "用戶登錄" in login_resp.text:
# Incorrect user
raise Exception("Incorrect login information")
elif "增值本地流動數據用量" in login_resp.text:
# Success
# Get session from cookie
session_id = login_resp.cookies.get("JSESSIONID")
return session_id
else:
raise Exception("Unknown error during login")
@staticmethod
def get_data_usage(session_id):
"""Get data usage. Return dict with three keys: total, used and left"""
current_timestamp = current_milli_time()
endpoint_url = DATA_USAGE_URL.format(current_timestamp)
response = requests.post(endpoint_url, cookies={"JSESSIONID": session_id})
html = BeautifulSoup(response.text, "html.parser")
total = ""
used = ""
left = ""
r = html.find_all("td")
for idx, i in enumerate(r):
if "服務計劃所包括之用量" in i.getText():
total = r[idx + 1].getText()
elif "已使用之用量" in i.getText():
used = r[idx + 1].getText()
elif "剩餘使用量" in i.getText():
left = r[idx + 1].getText()
return {"total": total, "used": used, "left": left}
def current_milli_time():
return round(time.time() * 1000)
if __name__ == "__main__":
n = input("Number:")
p = input("Password:")
session = SunMobile.login(n, p)
print(SunMobile.get_data_usage(session))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment