Selenium模擬選課

使用selenium+python實現無人看守選課。

用到的一些模塊

  • selenium

selenium在前面的文章中曾經介紹過,就是模擬瀏覽器的一個第三方模塊,通過提供的各種方法模擬控制browser,同時提供了無UI的Browserdriver,減少渲染開銷,提升運行速度.

  • time

本例中實現暫停掃描功能,防止服務器對IP封鎖

  • re

正則表達模塊,獲取相關數據

常用的方法

  • b=webdriver.PhantomJS()

開啓Selenium的一個webdriver實例,這裏使用的是無UI的PhantomJS,通過它進行對browser的操作

  • b.get(url)

url是我們想要request的網絡地址,get方法實際上就是我們在browser中地址欄填入url並回車訪問的過程

  • find_element_by_xpath

一系列的find_element_by方法,通過各種定位方法(Xpath、css-seletor、id、tagname)拿到需要操縱的元素句柄

  • element.send_keys(value)

在input或者其他可輸入標籤元素中填入keyword,在使用這個方法之前,建議使用element.clear()清楚之前的所有信息,因爲send_keys()方法是直接在後面append

  • element.get_attribute(attr)

獲取元素的屬性值,例如href、onclick

  • b.page_source

獲取當前driver停留頁面的源網頁代碼

  • re.findall(pattern,str)

re正則過濾,pattern是模式串,根據正則規則編寫的模式串,str是原始串,也就是需要匹配的串

實現

from selenium import webdriver
import time
import re
cc=webdriver.PhantomJS()
#身份認證,一次運行只需要運行一次
cc.get('http://auth.bupt.edu.cn/authserver/login?service=http%3a%2f%2fyjxt.bupt.edu.cn%2fULogin.aspx')
uname=cc.find_element_by_xpath('//*[@id="username"]')
uname.clear()
uname.send_keys('*********')
passwd=cc.find_element_by_xpath('//*[@id="password"]')
passwd.clear()
passwd.send_keys('*********')
cc.find_element_by_xpath('//*[@id="casLoginForm"]/input[4]').click()
xuankeurl='http://yjxt.bupt.edu.cn/Gstudent/Course/PlanCourseOnlineSel.aspx?EID=9kWb0OKGTBF2KzmBt5QNDZLXYu1Fldi6xwxV6Yb1wPA1TrsnKBRXgg==&UID=2016111552'
delaylist=[u'班級已全選滿',u'選課未開放',u'選課已結束']
cc.get(xuankeurl)
wantedcourse=cc.find_element_by_xpath('//*[@id="contentParent_dgData_hykFull_42"]')
restr=wantedcourse.get_attribute('onclick')
jumpurl=(re.findall("classFull\('\?(.+)','classFull'\);",restr))[0]
while True:
    cc.get(xuankeurl)
    wantedcourse=cc.find_element_by_xpath('//*[@id="contentParent_dgData_hykFull_42"]')
    if wantedcourse.text in delaylist:
        print(wantedcourse.text)
        time.sleep(5)
        pass
    else :
        cc.get('http://yjxt.bupt.edu.cn/Gstudent/Course/PlanClassSelFull.aspx?'+jumpurl)
        print(cc.page_source)
        break;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章