student.go 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528
  1. package student
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/base64"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "math/rand"
  12. "net/http"
  13. "os"
  14. "ouchn/config"
  15. "regexp"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/tebeka/selenium/chrome"
  22. "github.com/google/uuid"
  23. "github.com/go-vgo/robotgo"
  24. "github.com/syndtr/goleveldb/leveldb"
  25. "github.com/tebeka/selenium"
  26. "github.com/tidwall/gjson"
  27. )
  28. func GetRecord(filename string) map[string]bool {
  29. ret := map[string]bool{}
  30. fi, err := os.Open(filename)
  31. if err != nil {
  32. return ret
  33. }
  34. defer fi.Close()
  35. br := bufio.NewReader(fi)
  36. for {
  37. a, _, c := br.ReadLine()
  38. //fmt.Printf("xx:%s\n", a)
  39. if c == io.EOF {
  40. break
  41. }
  42. array := strings.Split(string(a), " ")
  43. if len(array) != 3 {
  44. continue
  45. }
  46. ret[array[0]] = true
  47. }
  48. return ret
  49. }
  50. func GetAcounts(filename string) ([][]string, error) {
  51. visited := GetRecord("record.txt")
  52. fi, err := os.Open(filename)
  53. if err != nil {
  54. return nil, err
  55. }
  56. defer fi.Close()
  57. ret := [][]string{}
  58. br := bufio.NewReader(fi)
  59. for {
  60. a, _, c := br.ReadLine()
  61. if c == io.EOF {
  62. break
  63. }
  64. array := strings.Split(string(a), ";")
  65. if len(array) != 3 {
  66. continue
  67. }
  68. if visited[array[0]] {
  69. //fmt.Printf("visited:%v\n", array[2])
  70. continue
  71. }
  72. item := []string{array[0], array[1], array[2]}
  73. ret = append(ret, item)
  74. }
  75. return ret, nil
  76. }
  77. func Displayed(by, elementName string) func(selenium.WebDriver) (bool, error) {
  78. return func(wd selenium.WebDriver) (ok bool, err error) {
  79. var el selenium.WebElement
  80. el, err = wd.FindElement(by, elementName)
  81. if err != nil {
  82. ok = false
  83. err = nil
  84. return
  85. }
  86. ok, err = el.IsDisplayed()
  87. return
  88. }
  89. }
  90. func Check415Error(wd selenium.WebDriver) error {
  91. e, err := wd.FindElement(selenium.ByTagName, "body")
  92. if err != nil {
  93. return err
  94. }
  95. text, _ := e.Text()
  96. str := "错误代码:415"
  97. if len(text) <= len(str) {
  98. return nil
  99. }
  100. if text[:len(str)] == str {
  101. return errors.New("访问受限")
  102. }
  103. return nil
  104. }
  105. func commonVerify(image string) string {
  106. //# 数英汉字类型
  107. //# 通用数英1-4位 10110
  108. //# 通用数英5-8位 10111
  109. //# 通用数英9~11位 10112
  110. //# 通用数英12位及以上 10113
  111. //# 通用数英1~6位plus 10103
  112. //# 定制-数英5位~qcs 9001
  113. //# 定制-纯数字4位 193
  114. //# 中文类型
  115. //# 通用中文字符1~2位 10114
  116. //# 通用中文字符 3~5位 10115
  117. //# 通用中文字符6~8位 10116
  118. //# 通用中文字符9位及以上 10117
  119. //# 定制-XX西游苦行中文字符 10107
  120. //# 计算类型
  121. //# 通用数字计算题 50100
  122. //# 通用中文计算题 50101
  123. //# 定制-计算题 cni 452
  124. config := map[string]interface{}{}
  125. config["image"] = image
  126. config["type"] = "30009"
  127. //config["extra"] = "click"
  128. config["token"] = "2EEYFMjDVpMTky-Z_BCgt_I14g4qq_D63S3NsQesfMc"
  129. configData, _ := json.Marshal(config)
  130. body := bytes.NewBuffer([]byte(configData))
  131. resp, err := http.Post("http://api.jfbym.com/api/YmServer/customApi", "application/json;charset=utf-8", body)
  132. defer resp.Body.Close()
  133. if err != nil {
  134. return ""
  135. }
  136. data, _ := ioutil.ReadAll(resp.Body)
  137. fmt.Println(string(data), err)
  138. return string(data)
  139. }
  140. func codeGetNew(data []byte, account string, token string) string {
  141. name := account + ".png"
  142. ioutil.WriteFile(name, data, 0666)
  143. //fmt.Println(name)
  144. defer func() {
  145. os.Remove(name)
  146. }()
  147. /* bodyBuffer := &bytes.Buffer{}
  148. bodyWriter := multipart.NewWriter(bodyBuffer)
  149. bodyWriter.WriteField("token", token)
  150. bodyWriter.WriteField("type", "local")
  151. fileWriter, _ := bodyWriter.CreateFormFile("file", name)
  152. */
  153. file, _ := os.Open(name)
  154. defer file.Close()
  155. fileInfo, _ := file.Stat()
  156. imageSize := fileInfo.Size()
  157. imageData := make([]byte, imageSize)
  158. _, err := file.Read(imageData)
  159. if err != nil {
  160. fmt.Println("保存文件失败")
  161. }
  162. base64Data := base64.StdEncoding.EncodeToString(imageData)
  163. respData := commonVerify(base64Data)
  164. fmt.Println("验证码识别结果:", respData)
  165. code := gjson.Get(respData, "code").Int()
  166. if code != 10000 {
  167. fmt.Println("验证码识别失败:", gjson.Get(respData, "msg").String())
  168. return ""
  169. }
  170. return gjson.Get(respData, "data.data").String()
  171. }
  172. /*
  173. func codeGet(data []byte, account string, token string) (bool, string) {
  174. name := account + ".png"
  175. ioutil.WriteFile(name, data, 0666)
  176. defer func() {
  177. os.Remove(name)
  178. }()
  179. bodyBuffer := &bytes.Buffer{}
  180. bodyWriter := multipart.NewWriter(bodyBuffer)
  181. bodyWriter.WriteField("token", token)
  182. bodyWriter.WriteField("type", "local")
  183. fileWriter, _ := bodyWriter.CreateFormFile("file", name)
  184. file, _ := os.Open(name)
  185. defer file.Close()
  186. io.Copy(fileWriter, file)
  187. contentType := bodyWriter.FormDataContentType()
  188. bodyWriter.Close()
  189. resp, err := http.Post("http://www.bhshare.cn/imgcode/", contentType, bodyBuffer)
  190. fmt.Println("验证码识别 err :", err)
  191. defer resp.Body.Close()
  192. resp_body, _ := ioutil.ReadAll(resp.Body)
  193. defer resp.Body.Close()
  194. fmt.Printf("验证码识别响应 %s\n", resp_body)
  195. timesExist := gjson.GetBytes(resp_body, "times").Exists()
  196. //fmt.Printf("%v,%v\n", gjson.GetBytes(resp_body, "times").Exists(),gjson.GetBytes(resp_body, "times").Int())
  197. if !timesExist {
  198. return false, ""
  199. }
  200. times := gjson.GetBytes(resp_body, "times").Int()
  201. if times < 1 {
  202. return true, ""
  203. }
  204. return false, gjson.GetBytes(resp_body, "data").String()
  205. }
  206. */
  207. var dbMutex sync.Mutex
  208. var db *leveldb.DB
  209. func TokenDbOpen() {
  210. dbMutex.Lock()
  211. defer dbMutex.Unlock()
  212. if db != nil {
  213. return
  214. }
  215. db, _ = leveldb.OpenFile("tokens", nil)
  216. }
  217. func TokenDbClear() {
  218. dbMutex.Lock()
  219. defer dbMutex.Unlock()
  220. if db == nil {
  221. return
  222. }
  223. for _, v := range config.Conf.CodeTokens {
  224. _ = db.Delete([]byte(v), nil)
  225. }
  226. }
  227. func TokenDbClose() {
  228. dbMutex.Lock()
  229. defer dbMutex.Unlock()
  230. if db == nil {
  231. return
  232. }
  233. db.Close()
  234. db = nil
  235. }
  236. func TokenDbGet(token string) string {
  237. dbMutex.Lock()
  238. defer dbMutex.Unlock()
  239. if db == nil {
  240. return ""
  241. }
  242. bytes, _ := db.Get([]byte(token), nil)
  243. return string(bytes)
  244. }
  245. func TokenDbPut(token string, value string) {
  246. dbMutex.Lock()
  247. defer dbMutex.Unlock()
  248. if db == nil {
  249. return
  250. }
  251. _ = db.Put([]byte(token), []byte(value), nil)
  252. }
  253. func codeGetHandle(data []byte, account string, tokens []string) string {
  254. //return "77,173|75,115|183,180"
  255. return codeGetNew(data, account, "")
  256. /*now := time.Now()
  257. day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
  258. dayStr := fmt.Sprintf("%d", day.Unix())
  259. for _, token := range tokens {
  260. if db != nil {
  261. str := TokenDbGet(token)
  262. if str == dayStr {
  263. continue
  264. }
  265. }
  266. timesIsLimit, code := codeGet(data, account, token)
  267. if timesIsLimit {
  268. TokenDbPut(token, dayStr)
  269. }
  270. if code != "" && code[0] >= '0' && code[0] <= '9' {
  271. return code
  272. }
  273. }
  274. return ""*/
  275. }
  276. func StartOneStudent(usernameText string, passwordText string, realName string) (service *selenium.Service, wd selenium.WebDriver, err error) {
  277. defer func() {
  278. if r := recover(); r != nil {
  279. err = errors.New(fmt.Sprintf("panic error %v-%v", err, r))
  280. }
  281. }()
  282. service, wd, err = StartOneStudentHandle(usernameText, passwordText, usernameText)
  283. return service, wd, err
  284. }
  285. func nextPage(wd selenium.WebDriver) []selenium.WebElement {
  286. next, err := wd.FindElement(selenium.ByXPATH, "//button[@class='btn-next']")
  287. if err != nil {
  288. return nil
  289. }
  290. disable, _ := next.GetAttribute("disabled")
  291. fmt.Printf("disable:%v\n", disable)
  292. if disable == "disabled" || disable == "true" {
  293. return nil
  294. }
  295. tryClick(wd, next)
  296. time.Sleep(5 * time.Second)
  297. buttons, _ := wd.FindElements(selenium.ByXPATH, "//a[text()='去学习']")
  298. if len(buttons) == 0 {
  299. return nil
  300. }
  301. return buttons
  302. }
  303. func tryChangePassSure(wd selenium.WebDriver) bool {
  304. act, err := wd.ActiveElement()
  305. if err != nil {
  306. fmt.Printf("find active element\n")
  307. return false
  308. }
  309. _, err = act.FindElement(selenium.ByXPATH, "//div[contains(text(), '请尽快修改密码')]")
  310. if err != nil {
  311. fmt.Printf("find active element to change pass\n")
  312. return false
  313. }
  314. sure, err := act.FindElement(selenium.ByXPATH, "//span[text()='确定']")
  315. if err != nil {
  316. fmt.Printf("find active element to change pass sure\n")
  317. return false
  318. }
  319. err = tryClick(wd, sure)
  320. if err != nil {
  321. fmt.Printf("find active element to click\n")
  322. return false
  323. }
  324. return true
  325. }
  326. func generateMoodleSession() string {
  327. // 生成随机的UUID作为moodleSession值
  328. id := uuid.New()
  329. return id.String()
  330. }
  331. func StartOneStudentHandle(usernameText string, passwordText string, realName string) (*selenium.Service, selenium.WebDriver, error) {
  332. var (
  333. //driverPath = `C:\Users\lqzlt\AppData\Local\Google\Chrome\Application\chromedriver.exe`
  334. driverPath = `./chromedriver.exe`
  335. port = 60002
  336. )
  337. // chrome服务
  338. service, err := selenium.NewChromeDriverService(driverPath, port, []selenium.ServiceOption{}...)
  339. if nil != err {
  340. return nil, nil, err
  341. }
  342. defer func() {
  343. //_ = service.Stop()
  344. }()
  345. // Connect to the WebDriver instance running locally.
  346. caps := selenium.Capabilities{"browserName": "chrome"}
  347. imagCaps := map[string]interface{}{
  348. "profile.managed_default_content_settings.cookies": 1,
  349. "same-site-by-default-cookies": 2,
  350. "cookies-without-same-site-must-be-secure": 2,
  351. "search_engine_is_default": false,
  352. }
  353. chromeCaps := chrome.Capabilities{
  354. Prefs: imagCaps,
  355. Path: "",
  356. ExcludeSwitches: []string{"enable-automation"},
  357. Args: []string{
  358. "--start-maximized",
  359. "--disable-blink-features=AutomationControlled",
  360. //"--no-sandbox",
  361. //"--disable-gpu-sandbox",
  362. "--accept-encoding=gzip, deflate, br",
  363. "--accept-language=zh-CN,zh;q=0.9",
  364. // "--cache-control=max-age=0",
  365. //"--abc=d",
  366. //"--load-extention=D:\\sql2struct",
  367. //fmt.Sprintf("--moodleSession=%s", generateMoodleSession()),
  368. //"--upgrade-insecure-requests=1",
  369. "--connection=keep-alive",
  370. "--accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
  371. "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
  372. },
  373. }
  374. caps.AddChrome(chromeCaps)
  375. wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
  376. if err != nil {
  377. return service, nil, errors.New(fmt.Sprintf("connect to the webDriver failed:%v\n", err))
  378. }
  379. //wd.MaximizeWindow("test")
  380. defer func() {
  381. //_ = wd.Close()
  382. }()
  383. //wd.Get("file:///C:/Users/lqzlt/Desktop/1.html")
  384. //time.Sleep(1*time.Second)
  385. //handleQuestionWebTest(wd)
  386. //time.Sleep(1000*time.Second)
  387. //return service, wd, nil
  388. //err = wd.Get("https://menhu.pt.ouchn.cn/")
  389. //err = wd.Get("https://iam.pt.ouchn.cn/am/UI/Login?realm=%2F&service=initService&goto=https%3A%2F%2Fiam.pt.ouchn.cn%2Fam%2Foauth2%2Fauthorize%3Fservice%3DinitService%26response_type%3Dcode%26client_id%3D345fcbaf076a4f8a%26scope%3Dall%26redirect_uri%3Dhttps%253A%252F%252Fmenhu.pt.ouchn.cn%252Fouchnapp%252Fwap%252Flogin%252Findex%26decision%3DAllow")
  390. err = wd.Get("https://iam.pt.ouchn.cn/am/UI/Login")
  391. if err != nil {
  392. return service, wd, err
  393. }
  394. if config.Conf.Timeout == 0 {
  395. config.Conf.Timeout = 20
  396. }
  397. if config.Conf.QuestionCount == 0 {
  398. config.Conf.QuestionCount = 2
  399. }
  400. //time.Sleep(2 * time.Second)
  401. fmt.Printf("查找登录按钮\n")
  402. // 进入登录页面
  403. err = wd.WaitWithTimeout(Displayed(selenium.ByID, "form_button"), time.Duration(config.Conf.Timeout)*time.Second)
  404. if err != nil {
  405. return service, wd, errors.New(fmt.Sprintf("获取登录页面失败:%v\n", err))
  406. }
  407. fmt.Printf("开始获取用户名按钮\n")
  408. username, err := wd.FindElement(selenium.ByID, "loginName")
  409. if err != nil {
  410. return service, wd, errors.New(fmt.Sprintf("获取用户名按钮:%v\n", err))
  411. }
  412. fmt.Printf("开始获取密码按钮\n")
  413. password, err := wd.FindElement(selenium.ByID, "password")
  414. if err != nil {
  415. return service, wd, errors.New(fmt.Sprintf("获取密码按钮:%v\n", err))
  416. }
  417. fmt.Printf("开始获取登录按钮\n")
  418. submit, err := wd.FindElement(selenium.ByID, "form_button")
  419. if err != nil {
  420. return service, wd, errors.New(fmt.Sprintf("获取登录按钮:%v\n", err))
  421. }
  422. fmt.Println("填充用户名:", usernameText)
  423. err = username.SendKeys(usernameText)
  424. if err != nil {
  425. return service, wd, errors.New(fmt.Sprintf("填充用户名:%v\n", err))
  426. }
  427. fmt.Println("填充密码:", passwordText)
  428. err = password.SendKeys(passwordText)
  429. if err != nil {
  430. return service, wd, errors.New(fmt.Sprintf("填充密码:%v\n", err))
  431. }
  432. /*fmt.Printf("开始获取验证码按钮\n")
  433. verifyCode, err := wd.FindElement(selenium.ByID, "captcha")
  434. if err != nil {
  435. return service, wd, errors.New(fmt.Sprintf("获取验证码按钮失败:%v\n", err))
  436. }
  437. fmt.Printf("点击验证码按钮\n")
  438. err = verifyCode.Click()
  439. if err != nil {
  440. return service, wd, errors.New(fmt.Sprintf("点击验证码按钮失败:%v\n", err))
  441. }*/
  442. err = tryClick(wd, submit)
  443. if err != nil {
  444. return service, wd, errors.New(fmt.Sprintf("点击登录:%v\n", err))
  445. }
  446. innerHeight, err := wd.ExecuteScript("return window.innerHeight", nil)
  447. if err != nil {
  448. }
  449. //fmt.Println("INNERhEIG:", innerHeight)
  450. fheight := innerHeight.(float64)
  451. aheight := int(fheight)
  452. //fmt.Println("addressBarHeight:", innerHeight, aheight)
  453. outerHeight, err := wd.ExecuteScript("return window.outerHeight", nil)
  454. if err != nil {
  455. }
  456. fheight = outerHeight.(float64)
  457. aheight = int(fheight) - aheight
  458. fmt.Println("addressBarHeight:", innerHeight, outerHeight, aheight)
  459. if config.Conf.CodeManual {
  460. time.Sleep(1 * time.Hour)
  461. /*count := 0
  462. for count < 60 {
  463. time.Sleep(1 * time.Second)
  464. value, _ := verifyCode.GetAttribute("value")
  465. if len(value) < 4 {
  466. continue
  467. }
  468. break
  469. }
  470. if count >= 60 {
  471. return service, wd, errors.New("未输入验证码")
  472. }*/
  473. } else {
  474. time.Sleep(1 * time.Second)
  475. // //div[@class='geetest_box_f3dbc8bc geetest_box']
  476. //image, err := wd.FindElement(selenium.ByXPATH, "//img[@id='kaptchaImage']")
  477. // time.Sleep(10 * time.Second)
  478. fmt.Println("获取验证码")
  479. err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "/html/body/div[4]/div[1]/div[1]"), time.Duration(config.Conf.Timeout)*time.Second)
  480. if err != nil {
  481. return service, wd, errors.New("验证码获取失败1111111")
  482. }
  483. image, err := wd.FindElement(selenium.ByXPATH, "/html/body/div[4]/div[1]/div[1]")
  484. if err != nil {
  485. return service, wd, errors.New("验证码获取失败")
  486. }
  487. fmt.Println("验证码获取成功")
  488. data, _ := image.Screenshot(false)
  489. code := codeGetHandle(data, usernameText, config.Conf.CodeTokens)
  490. if code == "" {
  491. return service, wd, errors.New("验证码识别失败\n")
  492. }
  493. //codeData := gjson.Get(code, "data").String()
  494. fmt.Println("CODE data:", code)
  495. codeList := strings.Split(code, "|")
  496. for _, v := range codeList {
  497. codeX := strings.Split(v, ",")
  498. if len(codeX) < 2 {
  499. break
  500. }
  501. x, _ := strconv.Atoi(codeX[0])
  502. y, _ := strconv.Atoi(codeX[1])
  503. point, _ := image.Location()
  504. robotgo.Move(x+point.X, y+point.Y+aheight)
  505. robotgo.Click("left")
  506. time.Sleep(1 * time.Second)
  507. }
  508. /*time.Sleep(time.Minute)
  509. os.Exit(1)*/
  510. /*err = verifyCode.SendKeys(code)
  511. if err != nil {
  512. return service, wd, errors.New(fmt.Sprintf("填充验证码:%v\n", err))
  513. }*/
  514. }
  515. imageSubmitButton, err := wd.FindElement(selenium.ByXPATH, "/html/body/div[4]/div[1]/div[1]/div[2]/div/div/div[2]")
  516. //err = submit.Click()
  517. err = tryClick(wd, imageSubmitButton)
  518. if err != nil {
  519. return service, wd, errors.New(fmt.Sprintf("点击提交失败:%v\n", err))
  520. }
  521. //time.Sleep(1200 *time.Second)
  522. //return service, wd, errors.New("登录测试")
  523. time.Sleep(2 * time.Second)
  524. tryChangePassSure(wd)
  525. // 进入学生主页
  526. err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//a[text()='去学习']"), time.Duration(config.Conf.Timeout)*time.Second)
  527. if err != nil {
  528. if !tryChangePassSure(wd) {
  529. return service, wd, errors.New(fmt.Sprintf("进入学生主页失败:%v\n", err))
  530. }
  531. time.Sleep(2 * time.Second)
  532. err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//a[text()='去学习']"), time.Duration(config.Conf.Timeout)*time.Second)
  533. if err != nil {
  534. fmt.Printf("find active element to find page\n")
  535. return service, wd, errors.New(fmt.Sprintf("进入学生主页失败:%v\n", err))
  536. }
  537. }
  538. fmt.Printf("进入学生主页\n")
  539. buttons, _ := wd.FindElements(selenium.ByXPATH, "//a[text()='去学习']")
  540. currentWindow, err := wd.CurrentWindowHandle()
  541. if err != nil {
  542. return service, wd, errors.New(fmt.Sprintf("获取当前窗口失败:%v\n", err))
  543. }
  544. for buttons != nil {
  545. for i := 0; i < len(buttons); i++ {
  546. button := buttons[i]
  547. text, _ := button.Text()
  548. if text != "去学习" {
  549. continue
  550. }
  551. if true {
  552. ptag, err := button.FindElement(selenium.ByXPATH, "./preceding-sibling::div/p")
  553. if err != nil {
  554. fmt.Printf("查找课程失败:%v\n", err)
  555. return service, wd, err
  556. }
  557. txt, _ := ptag.Text()
  558. array := strings.Split(txt, " ")
  559. if len(array) > 1 {
  560. txt = array[1]
  561. }
  562. txt = strings.TrimSpace(txt)
  563. if !checkCourseExist(config.Conf.Courses, txt) {
  564. fmt.Println("不执行课程:", txt)
  565. continue
  566. }
  567. fmt.Println("要执行课程:", txt)
  568. }
  569. //button.Click()
  570. tryClick(wd, button)
  571. //time.Sleep(60*time.Second)
  572. count := 0
  573. handled := ""
  574. // 等待新页面弹出
  575. for count < 5 {
  576. time.Sleep(1 * time.Second)
  577. handles, _ := wd.WindowHandles()
  578. if len(handles) > 1 {
  579. handled = handles[len(handles)-1]
  580. //
  581. wd.SwitchWindow(handled)
  582. break
  583. }
  584. count++
  585. }
  586. if count > 5 {
  587. continue
  588. }
  589. if err := Check415Error(wd); err != nil {
  590. return service, wd, err
  591. }
  592. // 处理课程
  593. //time.Sleep(4000 * time.Second)
  594. err = CourseHandle(wd, realName)
  595. if err != nil {
  596. return service, wd, err
  597. }
  598. //fmt.Printf("xxxxerr:%v\n", err)
  599. // 关闭当前课程窗口
  600. wd.CloseWindow(handled)
  601. // 切换到学生主页窗口(有进入学习按钮的窗口)
  602. wd.SwitchWindow(currentWindow)
  603. runtime.GC()
  604. }
  605. buttons = nextPage(wd)
  606. }
  607. return service, wd, err
  608. }
  609. // 等待url变化
  610. func waitUrl(wd selenium.WebDriver, url1 string, url2 string, count int) string {
  611. for count >= 0 {
  612. time.Sleep(100 * time.Millisecond)
  613. url, _ := wd.CurrentURL()
  614. if url != url1 && url != url2 {
  615. return url
  616. }
  617. count--
  618. }
  619. return ""
  620. }
  621. func getCookies(wd selenium.WebDriver) (string, error) {
  622. cookies, err := wd.GetCookies()
  623. if err != nil {
  624. return "", errors.New(fmt.Sprintf("获取cookie 失败,%v\n", err))
  625. }
  626. if len(cookies) == 0 {
  627. return "", errors.New(fmt.Sprintf("获取cookie 失败,%v\n", "cookie为空"))
  628. }
  629. ret := ""
  630. for _, v := range cookies {
  631. item := fmt.Sprintf("%s=%s", v.Name, v.Value)
  632. if ret == "" {
  633. ret = item
  634. continue
  635. }
  636. ret = ret + ";"
  637. ret = ret + item
  638. }
  639. return ret, nil
  640. }
  641. func checkCourseExist(courses []string, course string) bool {
  642. for _, v := range courses {
  643. if v == course {
  644. return true
  645. }
  646. }
  647. return false
  648. }
  649. type ElementInfo struct {
  650. Element selenium.WebElement
  651. }
  652. type AnswerInfo struct {
  653. Text string
  654. Radio *ElementInfo
  655. Ptag *ElementInfo
  656. }
  657. type QuestionInfo struct {
  658. Text string
  659. Tag int
  660. Number string
  661. AnswerArray []*AnswerInfo
  662. ChoosedAnswer []int
  663. }
  664. func GenerateRandom(length int) int {
  665. time.Sleep(1 * time.Microsecond)
  666. rand.Seed(time.Now().UnixNano())
  667. return rand.Intn(length)
  668. }
  669. // 计算题
  670. func shortAnswer(question QuestionInfo, questionM map[string][]string) error {
  671. if len(question.AnswerArray) == 0 {
  672. return errors.New(fmt.Sprintf("%s 选项为空", question.Text))
  673. }
  674. //fmt.Println("收集的答案000000000000000000000000:", questionM)
  675. str := TrimSpace(question.Text)
  676. str = ParseHan(str)
  677. str = fmt.Sprintf("%d-", question.Tag) + str
  678. //fmt.Println("问答题目1111111111111111111111111:", str)
  679. answerstrs, _ := questionM[str]
  680. //fmt.Println("问答答案2222222222222222222222222:", answerstrs)
  681. if len(answerstrs) == 0 {
  682. str = strings.TrimRight(str, "分")
  683. answerstrs, _ = questionM[str]
  684. if len(answerstrs) == 0 {
  685. return errors.New("没有答案")
  686. }
  687. }
  688. index := GenerateRandom(len(answerstrs))
  689. question.AnswerArray[0].Ptag.Element.Clear()
  690. question.AnswerArray[0].Ptag.Element.SendKeys(answerstrs[index])
  691. //fmt.Println("问答选择答案2222222222222222222222222:", answerstrs[index])
  692. time.Sleep(500 * time.Millisecond)
  693. return nil
  694. }
  695. func tryClick(wd selenium.WebDriver, element selenium.WebElement) error {
  696. array := []interface{}{element}
  697. _, err := wd.ExecuteScript("arguments[0].click()", array)
  698. if err != nil {
  699. fmt.Printf("按钮点击失败:%v\n", err)
  700. }
  701. return err
  702. }
  703. var questionTagM = map[int]string{
  704. 1: "单选题",
  705. 2: "判断题",
  706. 3: "多选题",
  707. 4: "计算题/简答题",
  708. }
  709. func getTagName(tag int) string {
  710. ret := questionTagM[tag]
  711. if ret == "" {
  712. return "未知题型"
  713. }
  714. return ret
  715. }
  716. // 题目号个数-本来就随机的题数, 再随机生成错误个数, 根据错误个数随机选择题号
  717. func getRandErrorNumber(emptyCount int, originNumber map[int]bool, maxNumber int) map[int]bool {
  718. questionCount := len(originNumber) - emptyCount
  719. if questionCount <= 2 || maxNumber <= 2 {
  720. return map[int]bool{}
  721. }
  722. count := 0
  723. if questionCount < 5 {
  724. count = 1
  725. } else {
  726. rand.Seed(time.Now().UnixNano())
  727. count = rand.Intn(3)
  728. if count == 0 {
  729. count = 1
  730. }
  731. }
  732. m := map[int]bool{}
  733. for len(m) < count {
  734. number := rand.Intn(maxNumber + 1)
  735. if originNumber[number] {
  736. m[number] = true
  737. }
  738. }
  739. return m
  740. }
  741. func random(count int) int {
  742. rand.Seed(time.Now().UnixNano())
  743. return rand.Intn(count)
  744. }
  745. func chooseAnswer2(wd selenium.WebDriver, questions []QuestionInfo, questionM map[string][]string) error {
  746. if config.Conf.NewStyle {
  747. return chooseAnswer2New(wd, questions, questionM)
  748. }
  749. emptyCount := 0
  750. if false {
  751. emptyCount = 3
  752. }
  753. // 选择或判断题目号
  754. originNumber := map[int]bool{}
  755. // 选择或判断最大题目号
  756. maxNumber := 0
  757. // 先收集答案
  758. for i, _ := range questions {
  759. questions[i].ChoosedAnswer = []int{}
  760. fmt.Printf("\n题目类型:%s\n", getTagName(questions[i].Tag))
  761. fmt.Printf("题目:%s\n", questions[i].Text)
  762. for _, v := range questions[i].AnswerArray {
  763. fmt.Printf("选项:%s\n", v.Text)
  764. }
  765. if questions[i].Tag == 4 {
  766. shortAnswer(questions[i], questionM)
  767. continue
  768. }
  769. if len(questions[i].AnswerArray) == 0 {
  770. return errors.New(fmt.Sprintf("%s 选项为空", questions[i].Text))
  771. }
  772. str := TrimSpace(questions[i].Text)
  773. str = ParseHan(str)
  774. //str = trimQuestionPrefix(str)
  775. str = fmt.Sprintf("%d-", questions[i].Tag) + str
  776. answerstrs, _ := questionM[str]
  777. if len(answerstrs) == 0 || answerstrs[0] == "" {
  778. emptyCount++
  779. if emptyCount > config.Conf.QuestionCount {
  780. return errors.New(fmt.Sprintf("%s 题库答案为空", questions[i].Text))
  781. }
  782. fmt.Printf("%s 题库答案为空, 空答案数小于%d,进行随机选择", questions[i].Text, config.Conf.QuestionCount)
  783. questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, random(len(questions[i].AnswerArray)))
  784. continue
  785. }
  786. find := 0
  787. // 单选
  788. if questions[i].Tag == 1 {
  789. //answerstrs = answerstrs[:1]
  790. }
  791. if questions[i].Tag == 3 {
  792. //fmt.Printf("*****************************************:%s,%v\n", questions[i].Text,answerstrs)
  793. }
  794. for _, answerstr := range answerstrs {
  795. if answerstr == "" {
  796. continue
  797. }
  798. for j, v := range questions[i].AnswerArray {
  799. if questions[i].Tag == 1 && find > 0 {
  800. break
  801. }
  802. right := false
  803. if questions[i].Tag == 3 {
  804. right = TrimSpace(answerstr) == TrimSpace(v.Text)
  805. } else {
  806. right = tryEqual(answerstr, TrimSpace(v.Text))
  807. }
  808. if right {
  809. fmt.Printf("选择答案:%s\n", answerstr)
  810. questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, j)
  811. originNumber[i] = true
  812. maxNumber = i
  813. //ppp, _ := v.Radio.Element.FindElement(selenium.ByXPATH, "./following-sibling::span")
  814. //txt, _ := ppp.Text()
  815. //fmt.Printf("kkkkkkkkkkkkkkkkkkk:%s,%s\n", txt, answerstr)
  816. if questions[i].Tag == 3 {
  817. //time.Sleep(10*time.Second)
  818. }
  819. find++
  820. //time.Sleep(1 * time.Second)
  821. break
  822. }
  823. }
  824. }
  825. if find == 0 {
  826. emptyCount++
  827. if emptyCount > config.Conf.QuestionCount {
  828. return errors.New(fmt.Sprintf("%s 题库答案为空2", questions[i].Text))
  829. }
  830. fmt.Printf("未找到匹配答案,题库中的答案有:%v\n", answerstrs)
  831. questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, random(len(questions[i].AnswerArray)))
  832. continue
  833. //return errors.New(fmt.Sprintf("%s 未找到匹配答案", questions[i].Text))
  834. }
  835. }
  836. // 选择答案, 先随机生成需故意填错的错误题号
  837. errorNumber := getRandErrorNumber(emptyCount, originNumber, maxNumber)
  838. defer func() {
  839. errorNumber = nil
  840. }()
  841. for i, _ := range questions {
  842. if len(questions[i].ChoosedAnswer) == 0 {
  843. continue
  844. }
  845. // 不需要故意填错
  846. if !errorNumber[i] {
  847. for _, v := range questions[i].ChoosedAnswer {
  848. err := tryClick(wd, questions[i].AnswerArray[v].Radio.Element)
  849. if err != nil {
  850. fmt.Printf("点击答案错误:%v\n", err)
  851. return err
  852. }
  853. time.Sleep(1 * time.Second)
  854. }
  855. continue
  856. }
  857. // 需要故意填错时,随机选择错误答案
  858. // 正确答案map
  859. cm := map[int]bool{}
  860. for _, j := range questions[i].ChoosedAnswer {
  861. cm[j] = true
  862. }
  863. // 可供选择的错误答案
  864. array := []int{}
  865. for j, _ := range questions[i].AnswerArray {
  866. if !cm[j] {
  867. array = append(array, j)
  868. }
  869. }
  870. // 随机生成索引
  871. arrayIndex := random(len(array))
  872. // 获取错误答案索引
  873. errorIndex := 0
  874. if len(array) > 0 {
  875. errorIndex = array[arrayIndex]
  876. } else {
  877. errorIndex = random(len(questions[i].AnswerArray))
  878. }
  879. err := tryClick(wd, questions[i].AnswerArray[errorIndex].Radio.Element)
  880. if err != nil {
  881. fmt.Printf("点击答案错误:%v\n", err)
  882. return err
  883. }
  884. time.Sleep(1 * time.Second)
  885. }
  886. return nil
  887. }
  888. func chooseAnswer2New(wd selenium.WebDriver, questions []QuestionInfo, questionM map[string][]string) error {
  889. emptyCount := 0
  890. if false {
  891. emptyCount = 3
  892. }
  893. // 选择或判断题目号
  894. originNumber := map[int]bool{}
  895. // 选择或判断最大题目号
  896. maxNumber := 0
  897. // 先收集答案
  898. for i, _ := range questions {
  899. questions[i].ChoosedAnswer = []int{}
  900. fmt.Printf("\n题目类型:%s\n", getTagName(questions[i].Tag))
  901. fmt.Printf("题目:%s\n", questions[i].Text)
  902. for _, v := range questions[i].AnswerArray {
  903. fmt.Printf("选项:%s\n", v.Text)
  904. }
  905. if questions[i].Tag == 4 {
  906. shortAnswer(questions[i], questionM)
  907. continue
  908. }
  909. if len(questions[i].AnswerArray) == 0 {
  910. return errors.New(fmt.Sprintf("%s 选项为空", questions[i].Text))
  911. }
  912. str := TrimSpace(questions[i].Text)
  913. str = ParseHan(str)
  914. //str = trimQuestionPrefix(str)
  915. str = fmt.Sprintf("%d-", questions[i].Tag) + str
  916. answerstrs, _ := questionM[str]
  917. if len(answerstrs) == 0 || answerstrs[0] == "" {
  918. emptyCount++
  919. if emptyCount > config.Conf.QuestionCount {
  920. return errors.New(fmt.Sprintf("%s 题库答案为空", questions[i].Text))
  921. }
  922. fmt.Printf("%s 题库答案为空, 空答案数小于%d,进行随机选择", questions[i].Text, config.Conf.QuestionCount)
  923. questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, random(len(questions[i].AnswerArray)))
  924. continue
  925. }
  926. find := 0
  927. // 单选
  928. if questions[i].Tag == 1 {
  929. //answerstrs = answerstrs[:1]
  930. }
  931. if questions[i].Tag == 3 {
  932. //fmt.Printf("*****************************************:%s,%v\n", questions[i].Text,answerstrs)
  933. }
  934. for _, answerstr := range answerstrs {
  935. if answerstr == "" {
  936. continue
  937. }
  938. for j, _ := range questions[i].AnswerArray {
  939. if questions[i].Tag == 1 && find > 0 {
  940. break
  941. }
  942. right := false
  943. if questions[i].Tag == 1 || questions[i].Tag == 3 {
  944. //right = TrimSpace(answerstr) == TrimSpace(v.Text)
  945. right = j == SelectAnswerFlagMap[answerstr]
  946. } else {
  947. //right = tryEqual(answerstr, TrimSpace(v.Text))
  948. right = j == JudgeAnswerMap[answerstr]
  949. }
  950. if right {
  951. fmt.Printf("选择答案:%s\n", answerstr)
  952. questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, j)
  953. originNumber[i] = true
  954. maxNumber = i
  955. //ppp, _ := v.Radio.Element.FindElement(selenium.ByXPATH, "./following-sibling::span")
  956. //txt, _ := ppp.Text()
  957. //fmt.Printf("kkkkkkkkkkkkkkkkkkk:%s,%s\n", txt, answerstr)
  958. if questions[i].Tag == 3 {
  959. //time.Sleep(10*time.Second)
  960. }
  961. find++
  962. //time.Sleep(1 * time.Second)
  963. break
  964. }
  965. }
  966. }
  967. if find == 0 {
  968. emptyCount++
  969. if emptyCount > config.Conf.QuestionCount {
  970. return errors.New(fmt.Sprintf("%s 题库答案为空2", questions[i].Text))
  971. }
  972. fmt.Printf("未找到匹配答案,题库中的答案有:%v\n", answerstrs)
  973. questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, random(len(questions[i].AnswerArray)))
  974. continue
  975. //return errors.New(fmt.Sprintf("%s 未找到匹配答案", questions[i].Text))
  976. }
  977. }
  978. // 选择答案, 先随机生成需故意填错的错误题号
  979. errorNumber := getRandErrorNumber(emptyCount, originNumber, maxNumber)
  980. defer func() {
  981. errorNumber = nil
  982. }()
  983. for i, _ := range questions {
  984. if len(questions[i].ChoosedAnswer) == 0 {
  985. continue
  986. }
  987. // 不需要故意填错
  988. if !errorNumber[i] {
  989. for _, v := range questions[i].ChoosedAnswer {
  990. err := tryClick(wd, questions[i].AnswerArray[v].Radio.Element)
  991. if err != nil {
  992. fmt.Printf("点击答案错误:%v\n", err)
  993. return err
  994. }
  995. time.Sleep(1 * time.Second)
  996. }
  997. continue
  998. }
  999. // 需要故意填错时,随机选择错误答案
  1000. // 正确答案map
  1001. cm := map[int]bool{}
  1002. for _, j := range questions[i].ChoosedAnswer {
  1003. cm[j] = true
  1004. }
  1005. // 可供选择的错误答案
  1006. array := []int{}
  1007. for j, _ := range questions[i].AnswerArray {
  1008. if !cm[j] {
  1009. array = append(array, j)
  1010. }
  1011. }
  1012. // 随机生成索引
  1013. arrayIndex := random(len(array))
  1014. // 获取错误答案索引
  1015. errorIndex := 0
  1016. if len(array) > 0 {
  1017. errorIndex = array[arrayIndex]
  1018. } else {
  1019. errorIndex = random(len(questions[i].AnswerArray))
  1020. }
  1021. err := tryClick(wd, questions[i].AnswerArray[errorIndex].Radio.Element)
  1022. if err != nil {
  1023. fmt.Printf("点击答案错误:%v\n", err)
  1024. return err
  1025. }
  1026. time.Sleep(1 * time.Second)
  1027. }
  1028. return nil
  1029. }
  1030. func chooseAnswer(wd selenium.WebDriver, questions []QuestionInfo, questionM map[string][]string) error {
  1031. // 正常选择答案
  1032. if !config.Conf.QuestionRandom {
  1033. return chooseAnswer2(wd, questions, questionM)
  1034. }
  1035. // 全部随机选
  1036. for i, _ := range questions {
  1037. fmt.Printf("\n题目类型:%s\n", getTagName(questions[i].Tag))
  1038. fmt.Printf("题目:%s\n", questions[i].Text)
  1039. for _, v := range questions[i].AnswerArray {
  1040. fmt.Printf("选项:%s\n", v.Text)
  1041. }
  1042. if questions[i].Tag == 4 {
  1043. shortAnswer(questions[i], questionM)
  1044. continue
  1045. }
  1046. if len(questions[i].AnswerArray) == 0 {
  1047. return errors.New(fmt.Sprintf("%s 选项为空", questions[i].Text))
  1048. }
  1049. str := TrimSpace(questions[i].Text)
  1050. str = ParseHan(str)
  1051. //str = trimQuestionPrefix(str)
  1052. str = fmt.Sprintf("%d-", questions[i].Tag) + str
  1053. answerstrs, _ := questionM[str]
  1054. if len(answerstrs) == 0 || answerstrs[0] == "" {
  1055. er := tryClick(wd, questions[i].AnswerArray[random(len(questions[i].AnswerArray))].Radio.Element)
  1056. if er != nil {
  1057. fmt.Printf("radio click:%v\n", er)
  1058. return er
  1059. }
  1060. time.Sleep(1 * time.Second)
  1061. continue
  1062. }
  1063. find := 0
  1064. // 单选
  1065. if questions[i].Tag == 1 {
  1066. //answerstrs = answerstrs[:1]
  1067. }
  1068. if questions[i].Tag == 3 {
  1069. //fmt.Printf("*****************************************:%s,%v\n", questions[i].Text,answerstrs)
  1070. }
  1071. for _, answerstr := range answerstrs {
  1072. if answerstr == "" {
  1073. continue
  1074. }
  1075. for _, v := range questions[i].AnswerArray {
  1076. if questions[i].Tag == 1 && find > 0 {
  1077. break
  1078. }
  1079. right := false
  1080. if questions[i].Tag == 3 {
  1081. right = TrimSpace(answerstr) == TrimSpace(v.Text)
  1082. } else {
  1083. right = tryEqual(answerstr, TrimSpace(v.Text))
  1084. }
  1085. if right {
  1086. fmt.Printf("选择答案:%s\n", answerstr)
  1087. er := tryClick(wd, v.Radio.Element)
  1088. if er != nil {
  1089. fmt.Printf("radio click:%v\n", er)
  1090. return er
  1091. }
  1092. //ppp, _ := v.Radio.Element.FindElement(selenium.ByXPATH, "./following-sibling::span")
  1093. //txt, _ := ppp.Text()
  1094. //fmt.Printf("kkkkkkkkkkkkkkkkkkk:%s,%s\n", txt, answerstr)
  1095. if questions[i].Tag == 3 {
  1096. //time.Sleep(10*time.Second)
  1097. }
  1098. find++
  1099. time.Sleep(1 * time.Second)
  1100. break
  1101. }
  1102. }
  1103. }
  1104. if find == 0 {
  1105. er := tryClick(wd, questions[i].AnswerArray[random(len(questions[i].AnswerArray))].Radio.Element)
  1106. if er != nil {
  1107. fmt.Printf("radio click:%v\n", er)
  1108. return er
  1109. }
  1110. //fmt.Printf("未找到匹配答案,题库中的答案有:%v\n", answerstrs)
  1111. continue
  1112. //return errors.New(fmt.Sprintf("%s 未找到匹配答案", questions[i].Text))
  1113. }
  1114. }
  1115. return nil
  1116. }
  1117. func getCourseId(src string) string {
  1118. array := strings.Split(src, "/")
  1119. if len(array) < 5 {
  1120. return ""
  1121. }
  1122. return array[4]
  1123. }
  1124. type CourseModule struct {
  1125. Name string
  1126. ModuleId string
  1127. }
  1128. func getUploadIds(moduleId string, cookie string) ([]int64, error) {
  1129. url := fmt.Sprintf("https://lms.ouchn.cn/api/activities/%s", moduleId)
  1130. request, err := http.NewRequest("GET", url, nil)
  1131. if err != nil {
  1132. return nil, err
  1133. }
  1134. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1135. request.Header.Set("Cookie", cookie)
  1136. request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
  1137. //request.Header.Set("Host", "chengdu.ouchn.cn")
  1138. client := http.Client{}
  1139. resp, err := client.Do(request)
  1140. if err != nil {
  1141. return nil, err
  1142. }
  1143. defer resp.Body.Close()
  1144. respBytes, err := ioutil.ReadAll(resp.Body)
  1145. if err != nil {
  1146. return nil, err
  1147. }
  1148. ret := []int64{}
  1149. uploads := gjson.GetBytes(respBytes, "uploads").Array()
  1150. for _, upload := range uploads {
  1151. id := upload.Get("id").Int()
  1152. ret = append(ret, id)
  1153. }
  1154. return ret, nil
  1155. }
  1156. func getCourseModules(courceId string, cookie string, specialCourse bool) ([]CourseModule, error) {
  1157. url := fmt.Sprintf("https://lms.ouchn.cn/api/courses/%s/modules", courceId)
  1158. request, err := http.NewRequest("GET", url, nil)
  1159. if err != nil {
  1160. return nil, err
  1161. }
  1162. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1163. request.Header.Set("Cookie", cookie)
  1164. request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
  1165. //request.Header.Set("Host", "chengdu.ouchn.cn")
  1166. client := http.Client{}
  1167. resp, err := client.Do(request)
  1168. if err != nil {
  1169. return nil, err
  1170. }
  1171. defer resp.Body.Close()
  1172. respBytes, err := ioutil.ReadAll(resp.Body)
  1173. if err != nil {
  1174. return nil, err
  1175. }
  1176. ret := []CourseModule{}
  1177. mos := gjson.GetBytes(respBytes, "modules").Array()
  1178. for _, mo := range mos {
  1179. if (len(mo.Get("syllabuses").Array())) == 0 && !specialCourse {
  1180. continue
  1181. }
  1182. item := CourseModule{}
  1183. item.ModuleId = fmt.Sprintf("%d", mo.Get("id").Int())
  1184. item.Name = mo.Get("name").String()
  1185. ret = append(ret, item)
  1186. }
  1187. return ret, nil
  1188. }
  1189. type ModuleSubInfo struct {
  1190. Name string
  1191. Id string
  1192. Stype string
  1193. SyllabusId int64
  1194. Type int // 1 page,2 vedio
  1195. }
  1196. type ModuleInfo struct {
  1197. TxtInfos []ModuleSubInfo
  1198. ExamInfos []ModuleSubInfo
  1199. VedioInfos []ModuleSubInfo
  1200. }
  1201. func GetModuleInfo(courseId string, moduleId string, cookie string) (*ModuleInfo, error) {
  1202. url := fmt.Sprintf("https://lms.ouchn.cn/api/course/%s"+
  1203. "/all-activities?module_ids=[%s]"+
  1204. "&activity_types=learning_activities,exams,classrooms,"+
  1205. "live_records,rollcalls&no-loading-animation=true", courseId, moduleId)
  1206. request, err := http.NewRequest("GET", url, nil)
  1207. if err != nil {
  1208. return nil, err
  1209. }
  1210. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1211. request.Header.Set("Cookie", cookie)
  1212. request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
  1213. //request.Header.Set("Host", "chengdu.ouchn.cn")
  1214. client := http.Client{Timeout: 60 * time.Second}
  1215. resp, err := client.Do(request)
  1216. if err != nil {
  1217. return nil, err
  1218. }
  1219. defer resp.Body.Close()
  1220. respBytes, err := ioutil.ReadAll(resp.Body)
  1221. if err != nil {
  1222. return nil, err
  1223. }
  1224. ret := &ModuleInfo{}
  1225. // 试题
  1226. exams := []ModuleSubInfo{}
  1227. examsArray := gjson.GetBytes(respBytes, "exams").Array()
  1228. for _, v := range examsArray {
  1229. item := ModuleSubInfo{}
  1230. item.Name = v.Get("title").String()
  1231. unikey := v.Get("unique_key").String()
  1232. array := strings.Split(unikey, "-")
  1233. if len(array) < 2 {
  1234. continue
  1235. }
  1236. item.Id = array[1]
  1237. exams = append(exams, item)
  1238. }
  1239. // 文档和视频
  1240. texts := []ModuleSubInfo{}
  1241. vedios := []ModuleSubInfo{}
  1242. array := gjson.GetBytes(respBytes, "learning_activities").Array()
  1243. for _, v := range array {
  1244. stype := v.Get("type").String()
  1245. syllabusId := v.Get("syllabus_id").Int()
  1246. item := ModuleSubInfo{}
  1247. item.Name = v.Get("title").String()
  1248. item.SyllabusId = syllabusId
  1249. item.Stype = stype
  1250. unikey := v.Get("unique_key").String()
  1251. array := strings.Split(unikey, "-")
  1252. if len(array) < 2 {
  1253. continue
  1254. }
  1255. item.Id = array[1]
  1256. if stype == "page" {
  1257. item.Type = 1
  1258. texts = append(texts, item)
  1259. vedios = append(vedios, item)
  1260. } else if stype == "online_video" || (stype == "web_link" && strings.Contains(item.Name, "视频")) || stype == "material" {
  1261. index := -1
  1262. item.Type = 2
  1263. for i := len(vedios) - 1; i >= 0; i-- {
  1264. if item.SyllabusId == vedios[i].SyllabusId {
  1265. index = i
  1266. break
  1267. }
  1268. }
  1269. if index == -1 || index == len(vedios)-1 {
  1270. vedios = append(vedios, item)
  1271. } else {
  1272. tmp := []ModuleSubInfo{}
  1273. tmp = append(tmp, vedios[:index+1]...)
  1274. tmp = append(tmp, item)
  1275. tmp = append(tmp, vedios[index+1:]...)
  1276. vedios = tmp
  1277. }
  1278. }
  1279. }
  1280. ret.ExamInfos = exams
  1281. ret.TxtInfos = texts
  1282. ret.VedioInfos = vedios
  1283. return ret, nil
  1284. }
  1285. func MakeTxtUrl(courseId string, moduleId string, id string) string {
  1286. return fmt.Sprintf("https://lms.ouchn.cn/course/%s/learning-activity/full-screen#/%s", courseId, id)
  1287. }
  1288. func MakeExamUrl(courseId string, moduleId string, id string) string {
  1289. return fmt.Sprintf("https://lms.ouchn.cn/course/%s/learning-activity/full-screen#/exam/%s", courseId, id)
  1290. }
  1291. func VedioCompleteHandle(cookie string, id string) error {
  1292. count := 0
  1293. start, end := int64(0), int64(1000)
  1294. for count < 5 {
  1295. finish, err := VedioComplete(cookie, id, start, end)
  1296. if err != nil {
  1297. return err
  1298. }
  1299. if finish < 100 {
  1300. start = end
  1301. end += 1000
  1302. count++
  1303. continue
  1304. }
  1305. return nil
  1306. }
  1307. return errors.New("视频处理失败")
  1308. }
  1309. func VedioComplete(cookie string, id string, start, end int64) (int64, error) {
  1310. url := fmt.Sprintf("https://lms.ouchn.cn/api/course/activities-read/%s", id)
  1311. //fmt.Printf("get sections:%v,%v\n", str, cookie)
  1312. m := map[string]interface{}{
  1313. "start": start,
  1314. "end": end,
  1315. }
  1316. content, _ := json.Marshal(m)
  1317. reader := bytes.NewReader(content)
  1318. fmt.Printf("post data:%s\n", content)
  1319. request, err := http.NewRequest("POST", url, reader)
  1320. if err != nil {
  1321. return 0, err
  1322. }
  1323. request.Header.Set("Content-Type", "application/json")
  1324. request.Header.Set("Cookie", cookie)
  1325. request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
  1326. client := http.Client{}
  1327. resp, err := client.Do(request)
  1328. if err != nil {
  1329. return 0, err
  1330. }
  1331. defer resp.Body.Close()
  1332. respBytes, err := ioutil.ReadAll(resp.Body)
  1333. if err != nil {
  1334. return 0, err
  1335. }
  1336. fmt.Printf("get bytes:%s\n", respBytes)
  1337. if gjson.GetBytes(respBytes, "activity_id").Int() == 0 {
  1338. return 0, errors.New("视频处理失败")
  1339. }
  1340. str := gjson.GetBytes(respBytes, "data").Get("completeness").String()
  1341. if str == "full" {
  1342. return 100, nil
  1343. }
  1344. if str == "part" {
  1345. return 10, nil
  1346. }
  1347. return gjson.GetBytes(respBytes, "data").Get("completeness").Int(), nil
  1348. }
  1349. func examHandleJump(wd selenium.WebDriver, courseId, moduleId, id string) error {
  1350. curl, _ := wd.CurrentURL()
  1351. fmt.Printf("url1:%s\n", curl)
  1352. url := MakeExamUrl(courseId, moduleId, id)
  1353. wd.Get(url)
  1354. time.Sleep(2 * time.Second)
  1355. curl, _ = wd.CurrentURL()
  1356. fmt.Printf("url2:%s\n", curl)
  1357. return nil
  1358. }
  1359. func examHandleStart(wd selenium.WebDriver) error {
  1360. // 点击答题按钮
  1361. err := wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//a[@class='button button-green take-exam ng-scope']"), time.Duration(config.Conf.Timeout)*time.Second)
  1362. if err != nil && strings.Contains(err.Error(), "timeout") {
  1363. curl, _ := wd.CurrentURL()
  1364. fmt.Printf("再次尝试:%s\n", curl)
  1365. wd.Get(curl)
  1366. time.Sleep(2 * time.Second)
  1367. err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//a[@class='button button-green take-exam ng-scope']"), time.Duration(config.Conf.Timeout)*time.Second)
  1368. }
  1369. if err != nil {
  1370. return err
  1371. }
  1372. button, err := wd.FindElement(selenium.ByXPATH, "//a[@class='button button-green take-exam ng-scope']")
  1373. if err != nil {
  1374. return err
  1375. }
  1376. //button.Click()
  1377. tryClick(wd, button)
  1378. fmt.Printf("点击答题按钮\n")
  1379. time.Sleep(2 * time.Second)
  1380. active, _ := wd.ActiveElement()
  1381. // 勾选同意框
  1382. chbox, err := active.FindElement(selenium.ByXPATH, "//input[@type='checkbox' and @name='confirm']")
  1383. if err != nil {
  1384. fmt.Printf("未找到同意勾选框:%v\n", err)
  1385. return err
  1386. }
  1387. //err = chbox.Click()
  1388. err = tryClick(wd, chbox)
  1389. if err != nil {
  1390. fmt.Printf("同意勾选框:%v\n", err)
  1391. return err
  1392. }
  1393. fmt.Printf("勾选同意框\n")
  1394. time.Sleep(1 * time.Second)
  1395. // 点击答题
  1396. button, err = active.FindElement(selenium.ByXPATH, "//button[text()='开始答题' or text()='继续答题']")
  1397. if err != nil {
  1398. fmt.Printf("未找到开始答题按钮:%v\n", err)
  1399. return err
  1400. }
  1401. //err = button.Click()
  1402. err = tryClick(wd, button)
  1403. if err != nil {
  1404. fmt.Printf("开始答题按钮:%v\n", err)
  1405. return err
  1406. }
  1407. fmt.Printf("弹窗中点击答题按钮\n")
  1408. time.Sleep(3 * time.Second)
  1409. return nil
  1410. }
  1411. func examHandleSimpleAnswer(wd selenium.WebDriver) ([]QuestionInfo, error) {
  1412. p, err := wd.FindElement(selenium.ByXPATH, "//div[@class='exam-subjects']/ol[@class='subjects-jit-display']")
  1413. if err != nil {
  1414. return nil, err
  1415. }
  1416. path := fmt.Sprintf("./following-sibling::li[@class='subject ng-scope short_answer']")
  1417. ret := []QuestionInfo{}
  1418. count := 0
  1419. for {
  1420. if count == 0 {
  1421. path = fmt.Sprintf("./li[@class='subject ng-scope short_answer']")
  1422. }
  1423. p, err = p.FindElement(selenium.ByXPATH, path)
  1424. if err != nil {
  1425. break
  1426. }
  1427. div, err := p.FindElements(selenium.ByXPATH, "./div/div/div/span/p")
  1428. if err != nil {
  1429. fmt.Printf("简答题目:%v\n", err)
  1430. break
  1431. }
  1432. txt, err := div[len(div)-1].Text()
  1433. fmt.Printf("简答题:%s,%v\n", txt, err)
  1434. item := QuestionInfo{Text: txt, Tag: 4}
  1435. ptag, err := p.FindElement(selenium.ByXPATH, "./div/div/div/div/div/div/div/p")
  1436. if err != nil {
  1437. fmt.Printf("简答题框未找到:%v\n", err)
  1438. break
  1439. }
  1440. if false {
  1441. ptag.Clear()
  1442. err = ptag.SendKeys("test test")
  1443. fmt.Printf("sendkeys error:%v\n", err)
  1444. }
  1445. anserItem := AnswerInfo{Ptag: &ElementInfo{Element: ptag}}
  1446. item.AnswerArray = append(item.AnswerArray, &anserItem)
  1447. ret = append(ret, item)
  1448. count++
  1449. }
  1450. if len(ret) == 0 {
  1451. return nil, errors.New("未找到题")
  1452. }
  1453. //fmt.Printf("yyyyyyyy:%v\n", ret)
  1454. return ret, nil
  1455. }
  1456. func examHandleSpecialQuestion(wd selenium.WebDriver) ([]QuestionInfo, error) {
  1457. fmt.Printf("正在搜集题目和选项请等待\n")
  1458. err := wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//div[@class='exam-subjects']/ol[@class='subjects-jit-display']"), time.Duration(config.Conf.Timeout)*time.Second)
  1459. if err != nil {
  1460. return nil, err
  1461. }
  1462. ol, err := wd.FindElement(selenium.ByXPATH, "//div[@class='exam-subjects']/ol[@class='subjects-jit-display']")
  1463. if err != nil {
  1464. return nil, err
  1465. }
  1466. time.Sleep(2 * time.Second)
  1467. lis1, _ := ol.FindElements(selenium.ByXPATH, "./li")
  1468. if len(lis1) == 0 {
  1469. return nil, errors.New("未找到题")
  1470. }
  1471. ret := []QuestionInfo{}
  1472. for _, li1 := range lis1 {
  1473. attr, _ := li1.GetAttribute("class")
  1474. tag := 0
  1475. if strings.Contains(attr, "true_or_false") {
  1476. tag = 2
  1477. }
  1478. if strings.Contains(attr, "single_selection") {
  1479. tag = 1
  1480. }
  1481. if strings.Contains(attr, "multiple_selection") {
  1482. tag = 3
  1483. }
  1484. if strings.Contains(attr, "short_answer") {
  1485. tag = 4
  1486. }
  1487. if tag == 0 {
  1488. continue
  1489. }
  1490. item := QuestionInfo{Tag: tag}
  1491. p, err := li1.FindElement(selenium.ByXPATH, "./div/div/div/span/p")
  1492. if err != nil {
  1493. return nil, err
  1494. }
  1495. txt, _ := p.Text()
  1496. item.Text = trimQuestionPrefix(txt)
  1497. //fmt.Println("1111111111111111112222222222222222222222222222222 text:", txt, item.Text)
  1498. if tag == 4 {
  1499. ptag, err := li1.FindElement(selenium.ByXPATH, "./div/div/div/div/div/div/div/p")
  1500. if err != nil {
  1501. fmt.Printf("简单题err:%v\n", err)
  1502. break
  1503. }
  1504. item.Text = TrimSpace(item.Text)
  1505. item.Text = ParseHan(item.Text)
  1506. /*itemTxt := ""
  1507. itemList := strings.Split(item.Text, ".")
  1508. if len(itemList) > 1 {
  1509. for index, v := range itemList {
  1510. if index == 0 {
  1511. continue
  1512. }
  1513. itemTxt = itemTxt + v
  1514. }
  1515. item.Text = strings.TrimSpace(itemTxt)
  1516. }
  1517. */
  1518. //fmt.Println("1111111111111111112222222222222222222222222222222 text finishi:", item.Text)
  1519. anserItem := &AnswerInfo{Ptag: &ElementInfo{Element: ptag}}
  1520. item.AnswerArray = append(item.AnswerArray, anserItem)
  1521. ret = append(ret, item)
  1522. continue
  1523. } else {
  1524. // 题目选项
  1525. ol, _ := li1.FindElement(selenium.ByXPATH, "./div/div/ol")
  1526. lis, _ := ol.FindElements(selenium.ByXPATH, "./li")
  1527. for _, li := range lis {
  1528. answerIterm := AnswerInfo{}
  1529. if tag == 2 {
  1530. radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
  1531. if err != nil {
  1532. return nil, err
  1533. }
  1534. answerIterm.Radio = &ElementInfo{Element: radio}
  1535. answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span")
  1536. if err != nil {
  1537. return nil, err
  1538. }
  1539. txt, _ := answer.Text()
  1540. answerIterm.Text = txt
  1541. //fmt.Printf("收集题目答案:%s\n", txt)
  1542. } else if tag == 1 || tag == 3 {
  1543. radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
  1544. if err != nil {
  1545. return nil, err
  1546. }
  1547. answerIterm.Radio = &ElementInfo{Element: radio}
  1548. answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span")
  1549. if err != nil {
  1550. return nil, err
  1551. }
  1552. txt, _ := answer.Text()
  1553. answerIterm.Text = txt
  1554. //fmt.Printf("收集题目答案:%s\n", txt)
  1555. if tag == 3 {
  1556. txt, _ := radio.GetAttribute("class")
  1557. if strings.Contains(txt, "ng-not-empty") {
  1558. //radio.Click()
  1559. tryClick(wd, radio)
  1560. }
  1561. }
  1562. //ppp, _ := radio.FindElement(selenium.ByXPATH, "./following-sibling::span")
  1563. //txt, _ = ppp.Text()
  1564. //fmt.Printf("kkkkkkkkkkkkkkkkkkkaa:%s,%s\n", txt, answerIterm.Text)
  1565. }
  1566. item.AnswerArray = append(item.AnswerArray, &answerIterm)
  1567. }
  1568. }
  1569. ret = append(ret, item)
  1570. }
  1571. return ret, nil
  1572. }
  1573. func trimQuestionPrefix(txt string) string {
  1574. if len(txt) < 2 {
  1575. return txt
  1576. }
  1577. regstr := `^[1-9][0-9]*(\.|、|.)`
  1578. //regstr := `^[1-9][0-9]*、`
  1579. reg := regexp.MustCompile(regstr)
  1580. prefix := reg.FindString(txt)
  1581. return txt[len(prefix):]
  1582. }
  1583. func examHandleQuestion(wd selenium.WebDriver, specialCourse bool) ([]QuestionInfo, error) {
  1584. if specialCourse {
  1585. return examHandleSpecialQuestion(wd)
  1586. }
  1587. err := wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//li[@class='subject ng-scope text']"), time.Duration(config.Conf.Timeout)*time.Second)
  1588. if err != nil {
  1589. return examHandleSimpleAnswer(wd)
  1590. }
  1591. questionClasses, _ := wd.FindElements(selenium.ByXPATH, "//li[@class='subject ng-scope text']")
  1592. ret := []QuestionInfo{}
  1593. for _, v := range questionClasses {
  1594. p, err := v.FindElement(selenium.ByXPATH, "./div/div/div/span/p[@class='ng-scope']")
  1595. if err != nil {
  1596. return nil, err
  1597. }
  1598. txt, _ := p.Text()
  1599. //fmt.Printf("题类%s\n", txt)
  1600. className := ""
  1601. tag := 0
  1602. // 题目类型
  1603. if strings.Contains(txt, "单项选择") || strings.Contains(txt, "单选") {
  1604. className = "subject ng-scope single_selection"
  1605. tag = 1
  1606. } else if strings.Contains(txt, "判断") {
  1607. className = "subject ng-scope true_or_false"
  1608. tag = 2
  1609. } else if strings.Contains(txt, "多项选择题") || strings.Contains(txt, "多选") {
  1610. tag = 3
  1611. className = "subject ng-scope multiple_selection"
  1612. } else if strings.Contains(txt, "计算题") || strings.Contains(txt, "简答题") {
  1613. tag = 4
  1614. className = "subject ng-scope short_answer"
  1615. }
  1616. if className == "" {
  1617. continue
  1618. }
  1619. p = v
  1620. path := fmt.Sprintf("./following-sibling::li[@class='%s']", className)
  1621. for {
  1622. item := QuestionInfo{Tag: tag}
  1623. // 题目
  1624. p, err = p.FindElement(selenium.ByXPATH, path)
  1625. if err != nil {
  1626. //fmt.Printf("err:%v\n", err)
  1627. break
  1628. }
  1629. x, err := p.FindElement(selenium.ByXPATH, "./div/div/div/span/p[@class='ng-scope']")
  1630. if err != nil {
  1631. break
  1632. }
  1633. txt, _ := x.Text()
  1634. // 题目描述
  1635. txt = strings.TrimSpace(txt)
  1636. item.Text = trimQuestionPrefix(txt)
  1637. if tag == 4 {
  1638. ptag, err := p.FindElement(selenium.ByXPATH, "./div/div/div/div/div/div/div/p")
  1639. if err != nil {
  1640. fmt.Printf("计算题err:%v\n", err)
  1641. break
  1642. }
  1643. anserItem := &AnswerInfo{Ptag: &ElementInfo{Element: ptag}}
  1644. item.AnswerArray = append(item.AnswerArray, anserItem)
  1645. ret = append(ret, item)
  1646. continue
  1647. }
  1648. // 题目选项
  1649. ol, _ := p.FindElement(selenium.ByXPATH, "./div/div/ol")
  1650. lis, _ := ol.FindElements(selenium.ByXPATH, "./li")
  1651. for _, li := range lis {
  1652. answerIterm := AnswerInfo{}
  1653. if tag == 2 {
  1654. radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
  1655. if err != nil {
  1656. return nil, err
  1657. }
  1658. answerIterm.Radio = &ElementInfo{Element: radio}
  1659. answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span")
  1660. if err != nil {
  1661. return nil, err
  1662. }
  1663. txt, _ := answer.Text()
  1664. answerIterm.Text = txt
  1665. } else if tag == 1 || tag == 3 {
  1666. radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
  1667. if err != nil {
  1668. return nil, err
  1669. }
  1670. answerIterm.Radio = &ElementInfo{Element: radio}
  1671. answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span/p")
  1672. if err != nil {
  1673. return nil, err
  1674. }
  1675. txt, _ := answer.Text()
  1676. answerIterm.Text = txt
  1677. if tag == 3 {
  1678. txt, _ := radio.GetAttribute("class")
  1679. if strings.Contains(txt, "ng-not-empty") {
  1680. //radio.Click()
  1681. tryClick(wd, radio)
  1682. }
  1683. }
  1684. //ppp, _ := radio.FindElement(selenium.ByXPATH, "./following-sibling::span")
  1685. //txt, _ = ppp.Text()
  1686. //fmt.Printf("kkkkkkkkkkkkkkkkkkkaa:%s,%s\n", txt, answerIterm.Text)
  1687. }
  1688. item.AnswerArray = append(item.AnswerArray, &answerIterm)
  1689. }
  1690. ret = append(ret, item)
  1691. }
  1692. }
  1693. return ret, nil
  1694. }
  1695. func examHandleQuestion2(wd selenium.WebDriver, specialCourse bool) ([]QuestionInfo, error) {
  1696. if specialCourse {
  1697. return examHandleSpecialQuestion(wd)
  1698. }
  1699. fmt.Printf("xxxxxx1\n")
  1700. err := wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//li[contains(@class, 'subject ng-scope short_answer')]"), time.Duration(config.Conf.Timeout)*time.Second)
  1701. if err == nil {
  1702. return examHandleSimpleAnswer(wd)
  1703. }
  1704. err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//li[contains(@class, 'subject ng-scope ')]"), time.Duration(config.Conf.Timeout)*time.Second)
  1705. if err != nil {
  1706. return nil, errors.New("未找到题")
  1707. }
  1708. fmt.Printf("xxxx2\n")
  1709. questionClasses, _ := wd.FindElements(selenium.ByXPATH, "//li[contains(@class, 'subject ng-scope ')]")
  1710. ret := []QuestionInfo{}
  1711. fmt.Printf("count:%v\n", len(questionClasses))
  1712. for _, v := range questionClasses {
  1713. attr, _ := v.GetAttribute("class")
  1714. fmt.Printf("attr:%v\n", attr)
  1715. tag := 0
  1716. if strings.Contains(attr, "single_selection") {
  1717. tag = 1
  1718. } else if strings.Contains(attr, "true_or_false") {
  1719. tag = 2
  1720. } else if strings.Contains(attr, "multiple_selection") {
  1721. tag = 3
  1722. } else if strings.Contains(attr, "short_answer") {
  1723. tag = 4
  1724. }
  1725. if tag == 0 {
  1726. continue
  1727. }
  1728. item := QuestionInfo{Tag: tag}
  1729. // 题目
  1730. p := v
  1731. x, err := p.FindElement(selenium.ByXPATH, "./div/div/div/span/p[@class='ng-scope']")
  1732. if err != nil {
  1733. x, err = p.FindElement(selenium.ByXPATH, "./div/div/div/span/p[@class='MsoNormal ng-scope']")
  1734. if err != nil {
  1735. break
  1736. }
  1737. }
  1738. txt, _ := x.Text()
  1739. // 题目描述
  1740. txt = strings.TrimSpace(txt)
  1741. item.Text = trimQuestionPrefix(txt)
  1742. fmt.Printf("题目描述:%v\n", txt)
  1743. if tag == 4 {
  1744. ptag, err := p.FindElement(selenium.ByXPATH, "./div/div/div/div/div/div/div/p")
  1745. if err != nil {
  1746. fmt.Printf("计算题err:%v\n", err)
  1747. break
  1748. }
  1749. anserItem := &AnswerInfo{Ptag: &ElementInfo{Element: ptag}}
  1750. item.AnswerArray = append(item.AnswerArray, anserItem)
  1751. ret = append(ret, item)
  1752. continue
  1753. }
  1754. // 题目选项
  1755. ol, _ := p.FindElement(selenium.ByXPATH, "./div/div/ol")
  1756. lis, _ := ol.FindElements(selenium.ByXPATH, "./li")
  1757. for _, li := range lis {
  1758. answerIterm := AnswerInfo{}
  1759. if tag == 2 {
  1760. radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
  1761. if err != nil {
  1762. return nil, err
  1763. }
  1764. answerIterm.Radio = &ElementInfo{Element: radio}
  1765. answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span")
  1766. if err != nil {
  1767. return nil, err
  1768. }
  1769. txt, _ := answer.Text()
  1770. answerIterm.Text = txt
  1771. fmt.Printf("选项:%v\n", answerIterm.Text)
  1772. } else if tag == 1 || tag == 3 {
  1773. radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
  1774. if err != nil {
  1775. return nil, err
  1776. }
  1777. answerIterm.Radio = &ElementInfo{Element: radio}
  1778. answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span/p")
  1779. if err != nil {
  1780. return nil, err
  1781. }
  1782. txt, _ := answer.Text()
  1783. answerIterm.Text = txt
  1784. if tag == 3 {
  1785. txt, _ := radio.GetAttribute("class")
  1786. if strings.Contains(txt, "ng-not-empty") {
  1787. //radio.Click()
  1788. tryClick(wd, radio)
  1789. }
  1790. }
  1791. fmt.Printf("选项:%v\n", answerIterm.Text)
  1792. //ppp, _ := radio.FindElement(selenium.ByXPATH, "./following-sibling::span")
  1793. //txt, _ = ppp.Text()
  1794. //fmt.Printf("kkkkkkkkkkkkkkkkkkkaa:%s,%s\n", txt, answerIterm.Text)
  1795. }
  1796. item.AnswerArray = append(item.AnswerArray, &answerIterm)
  1797. }
  1798. ret = append(ret, item)
  1799. }
  1800. return ret, nil
  1801. }
  1802. func examHandleMatch(wd selenium.WebDriver, questions []QuestionInfo, m map[string][]string) error {
  1803. err := chooseAnswer(wd, questions, m)
  1804. if err != nil {
  1805. if false {
  1806. fmt.Printf("err:%v\n", err)
  1807. c := ""
  1808. fmt.Printf("等待输入\n")
  1809. fmt.Scanln(&c)
  1810. m, _ = LoadXlsx(fmt.Sprintf("%s.xlsx", "思想道德修养与法律基础"))
  1811. return examHandleMatch(wd, questions, m)
  1812. }
  1813. return err
  1814. }
  1815. return nil
  1816. }
  1817. func tryEqual(a string, b string) bool {
  1818. if a == b {
  1819. return true
  1820. }
  1821. if !strings.Contains(a, b) {
  1822. return false
  1823. }
  1824. index := strings.Index(a, b)
  1825. for i := 0; i < index; i++ {
  1826. if (a[i] <= 'z' && a[i] >= 'a') || (a[i] >= '0' && a[i] <= '1') || (a[i] <= 'Z' && a[i] >= 'A') {
  1827. return false
  1828. }
  1829. }
  1830. for i := index + len(b); i < len(a); i++ {
  1831. if (a[i] <= 'z' && a[i] >= 'a') || (a[i] >= '0' && a[i] <= '1') || (a[i] <= 'Z' && a[i] >= 'A') {
  1832. return false
  1833. }
  1834. }
  1835. return true
  1836. }
  1837. func examHandleSubmit(wd selenium.WebDriver) error {
  1838. // 交卷
  1839. button1, err := wd.FindElement(selenium.ByXPATH, "//a[@class='button button-green ng-scope' and text()='交卷']")
  1840. if err != nil {
  1841. return err
  1842. }
  1843. //button1.Click()
  1844. tryClick(wd, button1)
  1845. time.Sleep(2 * time.Second)
  1846. // 弹窗中的确定
  1847. active, _ := wd.ActiveElement()
  1848. button2s, err := active.FindElements(selenium.ByXPATH, "//button[text()='确定']")
  1849. if err != nil {
  1850. return err
  1851. }
  1852. for _, button2 := range button2s {
  1853. txt, _ := button2.Text()
  1854. if txt == "确定" {
  1855. //button2.Click()
  1856. tryClick(wd, button2)
  1857. time.Sleep(2 * time.Second)
  1858. return nil
  1859. }
  1860. }
  1861. return errors.New("交卷未找到确定按钮")
  1862. }
  1863. func examHandle(wd selenium.WebDriver, courseId, moduleId, id string, qustionM map[string][]string, specialCourse bool) error {
  1864. cookie, _ := getCookies(wd)
  1865. finsh, submited, noScore := checkExamFinish(id, cookie)
  1866. if noScore {
  1867. fmt.Printf("不计分,该试题不做\n")
  1868. return nil
  1869. }
  1870. if finsh {
  1871. fmt.Printf("试题达到最大提交次数\n")
  1872. return nil
  1873. }
  1874. if submited {
  1875. isFinsh := checkExamScore(id, cookie)
  1876. if isFinsh {
  1877. fmt.Printf("已完成该试题,并满足分数\n")
  1878. return nil
  1879. } else {
  1880. fmt.Printf("已完成该试题,不满足分数,继续答题\n")
  1881. }
  1882. }
  1883. // 跳转页面
  1884. if err := examHandleJump(wd, courseId, moduleId, id); err != nil {
  1885. return err
  1886. }
  1887. // 点击答题按钮
  1888. if err := examHandleStart(wd); err != nil {
  1889. return err
  1890. }
  1891. // 收集题目和答案选项
  1892. questions, err := examHandleQuestion2(wd, specialCourse)
  1893. if err != nil {
  1894. fmt.Printf("examhandleQuestion:%v\n")
  1895. if strings.Contains(err.Error(), "未找到题") {
  1896. url, _ := wd.CurrentURL()
  1897. wd.Get(url)
  1898. fmt.Printf("再次尝试:%s\n", url)
  1899. questions, err = examHandleQuestion(wd, specialCourse)
  1900. if err != nil {
  1901. return err
  1902. }
  1903. }
  1904. }
  1905. if true {
  1906. //time.Sleep(4000 * time.Second)
  1907. }
  1908. fmt.Println("--------------------------------------------------------题目和答案:", questions)
  1909. // 匹配题库并选择答案
  1910. fmt.Printf("*****************开始匹配答案\n")
  1911. if err := examHandleMatch(wd, questions, qustionM); err != nil {
  1912. return err
  1913. }
  1914. fmt.Printf("examHandleMatch:%v\n", err)
  1915. if false {
  1916. //time.Sleep(4000*time.Second)
  1917. fmt.Println("请输入:")
  1918. sal := ""
  1919. fmt.Scanln(&sal)
  1920. //return nil
  1921. }
  1922. // 提交试卷
  1923. fmt.Printf("开始提交\n")
  1924. if config.Conf.SleepTime > 0 {
  1925. fmt.Printf("等待%d秒提交\n", config.Conf.SleepTime)
  1926. time.Sleep(time.Duration(config.Conf.SleepTime) * time.Second)
  1927. }
  1928. err = examHandleSubmit(wd)
  1929. fmt.Printf("examHandleSubmit:%v\n", err)
  1930. if false {
  1931. //time.Sleep(4000*time.Second)
  1932. fmt.Println("请输入2:")
  1933. sal := ""
  1934. fmt.Scanln(&sal)
  1935. }
  1936. return err
  1937. }
  1938. func checkExamScore(id string, cookie string) (finish bool) {
  1939. url := fmt.Sprintf("https://lms.ouchn.cn/api/exams/%s/submissions", id)
  1940. request, err := http.NewRequest("GET", url, nil)
  1941. if err != nil {
  1942. return false
  1943. }
  1944. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1945. request.Header.Set("Cookie", cookie)
  1946. request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
  1947. //request.Header.Set("Host", "chengdu.ouchn.cn")
  1948. client := http.Client{}
  1949. resp, err := client.Do(request)
  1950. if err != nil {
  1951. return false
  1952. }
  1953. defer resp.Body.Close()
  1954. respBytes, err := ioutil.ReadAll(resp.Body)
  1955. if err != nil {
  1956. return false
  1957. }
  1958. examScore := gjson.GetBytes(respBytes, "exam_score").Int()
  1959. fmt.Println("分数:", examScore, " 最低要求分数:", config.Conf.MinScore)
  1960. if int(examScore) >= config.Conf.MinScore {
  1961. return true
  1962. }
  1963. return false
  1964. }
  1965. func checkExamFinish(id string, cookie string) (finish bool, submited bool, noScore bool) {
  1966. url := fmt.Sprintf("https://lms.ouchn.cn/api/exams/%s", id)
  1967. request, err := http.NewRequest("GET", url, nil)
  1968. if err != nil {
  1969. return false, false, false
  1970. }
  1971. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  1972. request.Header.Set("Cookie", cookie)
  1973. request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
  1974. //request.Header.Set("Host", "chengdu.ouchn.cn")
  1975. client := http.Client{}
  1976. resp, err := client.Do(request)
  1977. if err != nil {
  1978. return false, false, false
  1979. }
  1980. defer resp.Body.Close()
  1981. respBytes, err := ioutil.ReadAll(resp.Body)
  1982. if err != nil {
  1983. return false, false, false
  1984. }
  1985. scorePercentage := gjson.GetBytes(respBytes, "score_percentage").String()
  1986. if scorePercentage == "0" || scorePercentage == "0.0" || scorePercentage == "0.00" {
  1987. return true, false, true
  1988. }
  1989. submitTimes := gjson.GetBytes(respBytes, "submit_times").Int()
  1990. submittedTimes := gjson.GetBytes(respBytes, "submitted_times").Int()
  1991. if submittedTimes > 0 {
  1992. submited = true
  1993. }
  1994. if submitTimes == submittedTimes && submitTimes > 0 {
  1995. return true, submited, false
  1996. }
  1997. return false, submited, false
  1998. }
  1999. func isSpecialCourse(title string) bool {
  2000. if title == "斜弱视技术" || title == "常见眼病诊断与处理" || title == "角膜接触镜并发症处理" {
  2001. return true
  2002. }
  2003. for _, v := range config.Conf.SpecialCourses {
  2004. if v == title {
  2005. return true
  2006. }
  2007. }
  2008. return false
  2009. }
  2010. func finishUploadId(uploadId int64, moduleId string, cookie string) error {
  2011. rBody := make(map[string]int64)
  2012. rBody["upload_id"] = uploadId
  2013. rByte, _ := json.Marshal(rBody)
  2014. url := fmt.Sprintf("https://lms.ouchn.cn/api/course/activities-read/%s", moduleId)
  2015. request, err := http.NewRequest("POST", url, bytes.NewBuffer(rByte))
  2016. if err != nil {
  2017. return err
  2018. }
  2019. request.Header.Set("Content-Type", "application/json")
  2020. request.Header.Set("Cookie", cookie)
  2021. request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
  2022. //request.Header.Set("Host", "chengdu.ouchn.cn")
  2023. client := http.Client{}
  2024. resp, err := client.Do(request)
  2025. if err != nil {
  2026. return err
  2027. }
  2028. defer resp.Body.Close()
  2029. respBytes, err := ioutil.ReadAll(resp.Body)
  2030. if err != nil {
  2031. return err
  2032. }
  2033. if true {
  2034. fmt.Println("do material resp:", string(respBytes))
  2035. }
  2036. return nil
  2037. }
  2038. func finishMaterial(uploadIds []int64, moduleId string, cookie string) {
  2039. for _, v := range uploadIds {
  2040. finishUploadId(v, moduleId, cookie)
  2041. time.Sleep(time.Duration(config.Conf.VideoInterval) * time.Second)
  2042. }
  2043. }
  2044. func doMaterial(moduleId string, cookie string) {
  2045. uploadIds, _ := getUploadIds(moduleId, cookie)
  2046. if len(uploadIds) > 0 {
  2047. finishMaterial(uploadIds, moduleId, cookie)
  2048. }
  2049. }
  2050. func CourseHandle(wd selenium.WebDriver, username string) error {
  2051. title, err := wd.Title()
  2052. if title == "" {
  2053. return nil
  2054. }
  2055. array := strings.Split(title, "-")
  2056. title = array[0]
  2057. title = strings.TrimSpace(title)
  2058. cookie, err := getCookies(wd)
  2059. if err != nil {
  2060. return err
  2061. }
  2062. fmt.Printf("***************正在处理%s课程%s\n", username, title)
  2063. specialCourse := isSpecialCourse(title)
  2064. fmt.Printf("is special:%v\n", specialCourse)
  2065. questionM, _ := LoadXlsx(fmt.Sprintf("%s.xlsx", title))
  2066. // 获取课程id
  2067. time.Sleep(2 * time.Second)
  2068. src, _ := wd.CurrentURL()
  2069. courseId := getCourseId(src)
  2070. if courseId == "" {
  2071. return errors.New("课程id获取失败")
  2072. }
  2073. fmt.Printf("课程id:%s\n", courseId)
  2074. // 获取课程所有栏目
  2075. modules, err := getCourseModules(courseId, cookie, specialCourse)
  2076. if err != nil {
  2077. return errors.New(fmt.Sprintf("获取module信息失败:%s", err.Error()))
  2078. }
  2079. fmt.Printf("modules:%v\n", modules)
  2080. examCount := 0
  2081. for _, module := range modules {
  2082. fmt.Printf("***课程:%s 栏目:%s\n", title, module.Name)
  2083. /*if specialCourse && (config.Conf.Target == 1 || config.Conf.Target == 3) && (!strings.Contains(module.Name, "形考任务") &&
  2084. !strings.Contains(module.Name, "形成性考核") &&
  2085. !strings.Contains(module.Name, "形考作业") &&
  2086. !strings.Contains(module.Name, "课程考核") &&
  2087. !strings.Contains(module.Name, "大作业") &&
  2088. !strings.Contains(module.Name, "考试考核")) {
  2089. fmt.Println("module name:", module.Name)
  2090. continue
  2091. }*/
  2092. if strings.Contains(module.Name, "专题一") ||
  2093. strings.Contains(module.Name, "专题二") ||
  2094. strings.Contains(module.Name, "专题三") ||
  2095. strings.Contains(module.Name, "专题四") ||
  2096. strings.Contains(module.Name, "专题五") ||
  2097. strings.Contains(module.Name, "总论 ") {
  2098. //continue
  2099. }
  2100. if false {
  2101. if !strings.Contains(module.Name, "专题三") {
  2102. continue
  2103. }
  2104. }
  2105. // 获取某栏目下的试题和视频数据
  2106. moduleInfo, err := GetModuleInfo(courseId, module.ModuleId, cookie)
  2107. if err != nil {
  2108. return errors.New(fmt.Sprintf("获取module(%s)详细信息失败:%s", module.Name, err.Error()))
  2109. }
  2110. //fmt.Println("2222222222222:", moduleInfo)
  2111. // 处理网页数据
  2112. if false {
  2113. for _, info := range moduleInfo.TxtInfos {
  2114. fmt.Printf("*****正在处理网页数据:%s\n", info.Name)
  2115. url := MakeTxtUrl(courseId, module.ModuleId, info.Id)
  2116. wd.Get(url)
  2117. count := 0
  2118. for count < 10 {
  2119. curl, _ := wd.CurrentURL()
  2120. if strings.Contains(curl, info.Id) {
  2121. time.Sleep(5 * time.Second)
  2122. break
  2123. }
  2124. count++
  2125. time.Sleep(1 * time.Second)
  2126. }
  2127. }
  2128. }
  2129. if (config.Conf.Target == 1 || config.Conf.Target == 2) && !strings.Contains(title, "国家开放大学学习指南") {
  2130. // 处理视频数据
  2131. for _, info := range moduleInfo.VedioInfos {
  2132. if config.Conf.HandlePage {
  2133. if info.Type == 1 {
  2134. fmt.Printf("*****正在处理网页数据:%s\n", info.Name)
  2135. url := MakeTxtUrl(courseId, module.ModuleId, info.Id)
  2136. wd.Get(url)
  2137. count := 0
  2138. for count < 10 {
  2139. curl, _ := wd.CurrentURL()
  2140. if strings.Contains(curl, info.Id) {
  2141. time.Sleep(5 * time.Second)
  2142. break
  2143. }
  2144. count++
  2145. time.Sleep(1 * time.Second)
  2146. }
  2147. }
  2148. }
  2149. if info.Type == 2 {
  2150. fmt.Printf("*****正在处理视频数据:%s\n", info.Name)
  2151. if info.Stype == "material" {
  2152. doMaterial(info.Id, cookie)
  2153. continue
  2154. }
  2155. url := MakeTxtUrl(courseId, module.ModuleId, info.Id)
  2156. wd.Get(url)
  2157. cookie, _ := getCookies(wd)
  2158. // 特殊视频
  2159. if info.Stype == "web_link" {
  2160. array := strings.Split(info.Name, ":")
  2161. if len(array) > 1 {
  2162. array[0] = array[1]
  2163. }
  2164. str := fmt.Sprintf("//iframe[contains(@ng-src, '%s')]", array[0])
  2165. wd.WaitWithTimeout(Displayed(selenium.ByXPATH, str), time.Duration(config.Conf.Timeout)*time.Second)
  2166. continue
  2167. }
  2168. err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//button[@class='mvp-toggle-play mvp-first-btn-margin']"), time.Duration(config.Conf.Timeout)*time.Second)
  2169. if err != nil {
  2170. wd.Get(url)
  2171. err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//button[@class='mvp-toggle-play mvp-first-btn-margin']"), time.Duration(config.Conf.Timeout)*time.Second)
  2172. if err != nil {
  2173. fmt.Printf("获取播放按钮失败\n")
  2174. }
  2175. continue
  2176. //return err
  2177. }
  2178. playButton, _ := wd.FindElement(selenium.ByXPATH, "//button[@class='mvp-toggle-play mvp-first-btn-margin']")
  2179. er := playButton.Click()
  2180. //er := tryClick(wd, playButton)
  2181. if er != nil {
  2182. fmt.Printf("播放点击失败:%v\n", er)
  2183. return er
  2184. }
  2185. //fmt.Printf("cookie:%s\n", cookie)
  2186. time.Sleep(time.Duration(config.Conf.VideoInterval) * time.Second)
  2187. //er = tryClick(wd, playButton)
  2188. //if er != nil {
  2189. // fmt.Printf("停止播放点击失败:%v\n", er)
  2190. //}
  2191. //wd.Get(fmt.Sprintf("https://lms.ouchn.cn/course/%s/ng#/my-stat", courseId))
  2192. //time.Sleep(2*time.Second)
  2193. err := VedioCompleteHandle(cookie, info.Id)
  2194. if err != nil {
  2195. fmt.Printf(" 视频%s处理失败(%s)\n", info.Name, err.Error())
  2196. return err
  2197. }
  2198. //time.Sleep(10000*time.Second)
  2199. }
  2200. }
  2201. }
  2202. if config.Conf.Target == 1 || config.Conf.Target == 3 {
  2203. // 处理试题数据
  2204. for _, info := range moduleInfo.ExamInfos {
  2205. fmt.Printf("*****正在处理试题数据:%s\n", info.Name)
  2206. if len(questionM) == 0 && !config.Conf.QuestionRandom {
  2207. fmt.Printf("无法处理试题,课程%s未提供答案\n", title)
  2208. break
  2209. }
  2210. //if !strings.Contains(info.Name, "考试任务二") {
  2211. // continue
  2212. //}
  2213. examCount++
  2214. fmt.Printf("count:%d\n", examCount)
  2215. // 测试用的
  2216. if examCount < 0 {
  2217. continue
  2218. }
  2219. err := examHandle(wd, courseId, module.ModuleId, info.Id, questionM, specialCourse)
  2220. if err != nil {
  2221. fmt.Printf(" 试题%s处理失败(%s)\n", info.Name, err.Error())
  2222. //time.Sleep(1000 * time.Second)
  2223. if strings.Contains(err.Error(), "选项为空") ||
  2224. strings.Contains(err.Error(), "答案为空") {
  2225. continue
  2226. }
  2227. return err
  2228. }
  2229. time.Sleep(1 * time.Second)
  2230. //time.Sleep(1000*time.Second)
  2231. }
  2232. //time.Sleep(1000*time.Second)
  2233. }
  2234. // 再次处理网页数据
  2235. if true {
  2236. for i := 0; i < config.Conf.VisitCount; i++ {
  2237. for _, info := range moduleInfo.TxtInfos {
  2238. fmt.Printf("*****正在点击网页数据:%s\n", info.Name)
  2239. url := MakeTxtUrl(courseId, module.ModuleId, info.Id)
  2240. wd.Get(url)
  2241. count := 0
  2242. for count < 10 {
  2243. curl, _ := wd.CurrentURL()
  2244. if strings.Contains(curl, info.Id) {
  2245. time.Sleep(2 * time.Second)
  2246. break
  2247. }
  2248. count++
  2249. time.Sleep(1 * time.Second)
  2250. }
  2251. }
  2252. }
  2253. }
  2254. }
  2255. if true {
  2256. //time.Sleep(1000*time.Second)
  2257. }
  2258. return nil
  2259. }