CQWLGBXY

#-*- codeing = utf-8 -*- 
#@Time : 2021/11/18 16:53
#@Author :谭煜琦
#@File : 网络*学院WEB端.py
#@Software: PyCharm

from  selenium import  webdriver
import  time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

# path_webdriver='D:\webdrivers\chromedriver.exe'
UA_agent =  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
opt=webdriver.ChromeOptions()
# opt.add_argument('--user-agent=%s' % UA_agent)
opt.add_argument("--mute-audio")
path_webdriver='d:\driver\chromedriver.exe'
driver = webdriver.Chrome(executable_path=path_webdriver,options=opt)

#获取轨迹
def get_track(distance):      # distance为传入的总距离
    # 移动轨迹
    track=[]
    # 当前位移
    current=0
    # 减速阈值
    mid=distance*4/5
    # 计算间隔
    t=0.5
    # 初速度
    v=30

    while current<distance:
        if current<mid:
            # 加速度为2
            a=30
        else:
            # 加速度为-2
            a=-3
        v0=v
        # 当前速度
        v=v0+a*t
        # 移动距离
        move=v0*t+1/2*a*t*t
        # 当前位移
        current+=move
        # 加入轨迹
        track.append(round(move))
    return track#
#移动
def move_to_gap(slider,tracks):     # slider是要移动的滑块,tracks是要传入的移动轨迹
    ActionChains(driver).click_and_hold(slider).perform()
    for x in tracks:
        ActionChains(driver).move_by_offset(xoffset=x,yoffset=0).perform()
    time.sleep(0.5)
    ActionChains(driver).release().perform()
#读取账号密码
def read_passWord(path='账号密码.txt'):
    with open(path,'r') as f:
        data=f.readlines()
        return data[0][:-1],data[1]


# 关闭除了主界面所有标签页,并且切回到选课界面
def close_weblist(main_handle):
    handles=driver.window_handles
    for handle in handles:
        driver.switch_to.window(handle)
        if handle!=main_handle:
            driver.close()
    driver.switch_to.window(main_handle)

#切换到指定标签
def switch_windows(web_title):
    handles=driver.window_handles
    for handle in handles:
        driver.switch_to.window(handle)
        if driver.title==web_title:
            break

#登录
def log_web(url='https://cqgj.12371.gov.cn/'):
    userName, passWord = read_passWord()
    driver.implicitly_wait(10)
    driver.get(url)
    driver.maximize_window()

    #登录账号
    log_button=driver.find_element_by_xpath('//span[contains(text(),"登录")]')
    log_button.click()
    input_userName=driver.find_element_by_xpath('//div[@class="username"]/input')
    input_passWord=driver.find_element_by_xpath('//div[@class="password"]/input[@id]')

    input_userName.clear()
    input_passWord.clear()
    input_userName.send_keys(userName)
    input_passWord.send_keys(passWord)
    #输入验证码
    try:
        input_ValidateCode = driver.find_element_by_xpath('//div[@class="validate"]/input')
    except:
        print('该次登录无验证码\n')
    else:
        input_ValidateCode.clear()
        input_ValidateCode.send_keys(input('请输入验证码:'))
    #点击登录
    login_button = driver.find_element_by_xpath('//div[@class="login-btn"]')
    login_button.click()

    #点击课程中心
    time.sleep(5)
    driver.implicitly_wait(10)
    pagesourse=driver.page_source
    url_course=driver.find_element_by_xpath('//li[@role="presentation"]/a[@ui-sref="courseCenter"]').get_attribute('href')
    driver.get(url_course)
    main_handle=driver.current_window_handle
    return  main_handle
#选课
def selcct_lesson(main_handle):
    #获取课程链接
    courseList = driver.find_elements_by_xpath('//div[@class="block3 pull-left"]/div[@class="line line1"]//a')
    courseSelectionStatus=driver.find_elements_by_xpath('//div[@class="line line2"]//span[@class="highlight ng-binding"]')

    for i in range(len(courseList)):
        driver.implicitly_wait(10)
        actions = ActionChains(driver)
        # 在新的标签页打开“课程详情”页面,保证状态为未选课状态
        if courseSelectionStatus[i].get_attribute('textContent')=='未选课':
            actions.key_down(Keys.CONTROL).click(courseList[i]).key_up(Keys.CONTROL).perform()
        else:
            continue
        # actions.key_down(Keys.CONTROL).click(courseList[i]).key_up(Keys.CONTROL).perform()
        #切换窗口
        driver.switch_to.window(driver.window_handles[-1])
        #获取播放链接
        time.sleep(1.5)
        driver.implicitly_wait(15)
        driver.find_element_by_xpath('//td[@class="listtb4 cur_title"]/a').click()
        time.sleep(1.5)
        #切换窗口
        switch_windows('课程播放')

        #拖动滑块验证
        driver.refresh()
        time.sleep(1)
        handle_bg=driver.find_element_by_xpath('//div[@class="handler handler_bg"]')#定位滑块
        move_to_gap(handle_bg, get_track(300))
        # 如果是有继续学习按钮的中断该次循环
        time.sleep(3)
        try:
            driver.find_element_by_xpath('//button[@class="continue-study"]')
        except:
            # pass
            print(driver.title)
        else:
            close_weblist(main_handle)
            continue

        #检测弹窗
        while True:
            try:
                #当前是否有答题环节
                submitButton = driver.find_element_by_xpath('//button[@ng-click="submitQues()"]')  # 提交按钮
            except:
                pass
            else:
                selectAnswer()
                submitButton.click()

            #当前视频进度
            try:
                driver.find_element_by_id("myplayer_display_button_replay")
            except:
                time.sleep(1.5)
            else:
                close_weblist(main_handle)
                time.sleep(35)
                break


#选择正确答案
def selectAnswer():
    answers = driver.find_elements_by_xpath('//input[@type="radio"]/..')
    question = driver.find_element_by_xpath('//div[@class="question-name ng-binding"]').get_attribute('textContent')
    print(question)
    question = question.split('=')[0]
    split_word = '+'
    for i in question:
        if not (i.isdigit()):
            split_word = i
    x, y = int(question.split(split_word)[0]), int(question.split(split_word)[1])
    if split_word == '+':
        true_answer = x + y
    elif split_word == '-':
        true_answer = x - y
    elif split_word == '*':
        true_answer = x * y
    else:
        true_answer = x / y

    for answer in answers:
        if str(true_answer) in answer.get_attribute('textContent'):
            answer.find_element_by_xpath('./input').click()
#学习
def learning(main_handle):
    #筛选单视频
    driver.find_element_by_xpath('//div[@class="tag"]/span[contains(text(), "单视频课件")]').click()
    time.sleep(3)
    for i in range(1,100):
        selcct_lesson(main_handle)
        nextpage=driver.find_element_by_xpath('//span[contains(text(),"下一页")]')
        ActionChains(driver).move_to_element_with_offset(nextpage,10,10).click().perform()
        time.sleep(2)


if __name__ == "__main__":
    main_handle=log_web()
    driver.refresh()
    learning(main_handle)
    pass

用selenium写的自动化程序,仅供研究学习,不得用于盈利。

代码写的很乱,也不想重构了,就这样吧。



上一篇:【笔记】【字符串】c++的输入总结


下一篇:selenium中如何判断元素是否出现?