get ccu moodle course info

. . . .
.

https://ecourse2.ccu.edu.tw

import requests
import getpass
import time
from bs4 import BeautifulSoup

# Login information
USERNAME = str(input('Student_ID: '))
PASSWORD = str(getpass.getpass('Password: '))
LOGIN_URL = 'https://ecourse2.ccu.edu.tw/login/index.php'
###

# Target URL
URL = 'https://ecourse2.ccu.edu.tw/my/'
URL_CLASS = 'https://ecourse2.ccu.edu.tw/local/courseutility/teachinginfo.php?id='
###

# Get request and find login token
print('Login.... ', end='')
session_requests = requests.Session()
res = session_requests.get(LOGIN_URL)
soup = BeautifulSoup(res.text, "html.parser")
print('OK')
print('Get token.... ', end='')
TOKEN = soup.find('input', {'name':'logintoken'})['value']
print('OK')
###

# Header and data for POST
headers = {
    'Host': 'ecourse2.ccu.edu.tw',
    'Connection': 'keep-alive',
    'Content-Length': '83',
    'Cache-Control': 'max-age=0',
    'Origin': 'https://ecourse2.ccu.edu.tw',
    'Upgrade-Insecure-Requests': '1',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Referer': LOGIN_URL,
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7'
}

payload = {
    'username': USERNAME,
    'password': PASSWORD,
    'logintoken': TOKEN
}
###

# POST request(login moodle)
print('POST the requests... ', end='')
res = session_requests.post(LOGIN_URL, data = payload, headers = headers)
###

# GET request if login successfully
soup = BeautifulSoup(res.text, "html.parser")

if(soup.find("div", attrs={"class": "logininfo"}).text == "您尚未登入"):
    print('FAIL')
else:
    print('OK')
    print('GET the requests... ', end='')
    res = session_requests.get(URL)
    print('OK')
    print('=========================')
    # Show student name
    soup = BeautifulSoup(res.text, "html.parser")
    print('Student: [' + soup.find("span", class_="usertext mr-1").text + ']')
    ###

    # Get all class
    classes = soup.find("ul", attrs={"class", "dropdown-menu"})

    for cla in classes:
        class_name = cla.text
        class_id = cla.a["href"].split('=')[1]
        res = session_requests.get(URL_CLASS + class_id)
        soup = BeautifulSoup(res.text, "html.parser")
        class_email = soup.find("li", attrs={"class":"contentnode"})
        # print(str(class_name).ljust(22), "\t", class_id, "\t", class_email.a.text)
        print("{0:{3}<30} {1:^4} {2:^15}".format(class_name, class_id, class_email.a.text, chr(12288)))
    ###

res.close()


Tags: CCU