current position:Home>Daily automatic health punch in (Python + Tencent cloud server)

Daily automatic health punch in (Python + Tencent cloud server)

2022-02-01 22:41:36 Tuessen

Automatic health clock in every day (Python+ Tencent cloud server )

1. Configuration requires

python3.7,Chrome perhaps Edeg browser ,Chrome Drive or Edge drive

# Need configuration selenium library ,baidu-aip library ,pillOW library , Execute the following command at the terminal 
pip install selenium
pip install pillow
pip install baidu-aip
 Copy code 

2. Realization function

1. Simulated Login to rap University micro service , Need Baidu OCR Intelligent identification API Interface identification verification code ( Free access )

2. Fill in the virtual location information , notes : The rest of the information remains the information of the previous day

3. Feedback clock in information to QQ mailbox , notes : You need to configure it yourself POP3/ SMTP service

4. Hang to Tencent cloud service , Automatic clock in every day

3. Reference link

Baidu OCR Intelligent identification API Call link

QQ Mailbox configuration link

Tencent runs on the ECS ( free 1 Months ) Choose a lightweight application server , I chose it linux System , The example here is also linux

4.linux Server configuration

Refer to Tencent documentation , Remote login linux example

1. With root Sign in

2. download Python3.7, upgrade pip,yum, Replace domestic sources

3. Installation Library , Execute the following command

pip3 install selenium
pip3 install pillow
pip3 install baidu-aip
 Copy code 

4. stay linux Install Google browser and driver on

In the catalog /etc/yum.repos.d/ Next new file google-chrome.repo

cd /etc/yum.repos.d/
vim google-chrome.repo
 Copy code 

vim Name edit google-chrome.repo file , Enter the following :

[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
 Copy code 

Specific operation : Press i Insert , Press Esc, then Shift+;, Input qw, Then press Enter sign out

Install browser , Enter the following commands in turn

yum -y install google-chrome-stable --nogpgcheck

#  Check version information 
google-chrome --version
#  find google_chrome route : My corresponding path is /usr/bin/google-chrome, Enter a path to create a soft connection 
which google-chrome
#  Create a soft connection 
ln -s /usr/bin/google-chrome /bin/chrome

#  Installation driver 
wget https://npm.taobao.org/mirrors/chromedriver/88.0.4324.96/chromedriver_linux64.zip
#  decompression 
yum -y install zip
unzip chromedriver_linux64.zip

#  Transfer chromedriver To /user/bin Under the table of contents 
sudo mv chromedriver /usr/bin

#  solve root function chrome problem 
vim /opt/google/chrome/google-chrome
#  Change the last line to read :
exec -a "$0" "$HERE/chrome" "[email protected]" --no-sandbox $HOME
 Copy code 

take Python The AutoRun program writes linux in :

vim automatic.py
#  Then copy the program in 
 Copy code 

test run :

python3 automatic.py
 Copy code 

utilize crontab Timed operation python Script :( Enter the following command )

crontab -e

#  From left to right, it indicates points in turn 、 when 、 Japan 、 month 、 Zhou , Set to every day 0:01 Automatic clock in 
1 0 * * * /usr/bin/python3 /root/automatic.py

#  Start the service 
service crond restart
 Copy code 

5. Code section

Explained in detail

import sys
import time
from aip import AipOcr
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from PIL import Image
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

class LogIn:
    def __init__(self, user, passwd, path, lat=30.630869, long=104.083748):
        self.target = 'https://wfw.scu.edu.cn/ncov/wap/default/index'  #  Rap University micro service address 
        self.username = str(user)  #  user name 
        self.password = str(passwd)  #  password 
        self.lat = lat  #  latitude 
        self.long = long  #  longitude 
        self.path = path


    def main(self):
        attempt = 0
        print('\n Get ready ')
        chrome_options = webdriver.ChromeOptions()
        #  Set no interface display parameters , Because I want to put it in linux Running on the server , Unable to display interface , When debugging, you need to comment out the following five lines , Show chrome Interface 
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('window-size=1920x1080')
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--hide-scrollbars')
        chrome_options.add_argument('--headless')

        s = Service(self.path)
        browser = webdriver.Chrome(service=s, options=chrome_options)#  load  chromedriver, use edge If you want to download edgedriver
        print(' Start ')
        while True:
            browser.delete_all_cookies()  #  Empty cookie
            browser.get(self.target)
            try:  #  Switch to account password login 
                browser.switch_to.frame('loginIframe')  #  Switch frame
                switch_element = WebDriverWait(browser, 10).until(
                    EC.element_to_be_clickable((By.XPATH, '/html/body/div/div/div[2]/div[2]/div[1]/div/div[3]'))
                ) #  Find the corresponding element location 
                switch_element.click() #  Click to switch 
            except Exception as error:
                print('network wrong...\n', error)

            #  Enter account number and password 
            input_user = browser.find_element(by=By.XPATH, value='/html/body/div/div/div[2]/div[2]/div[2]/div[3]/div[1]/div[2]/div/input')
            input_user.send_keys(self.username)
            input_pwd = browser.find_element(by=By.XPATH, value='/html/body/div/div/div[2]/div[2]/div[2]/div[3]/div[2]/div[2]/div/input')
            input_pwd.send_keys(self.password)
            time.sleep(1)

            #  Screenshot verification code and identification ( Baidu cloud used here is free OCR), You need to register yourself , No, you can refer to this blog :https://www.cnblogs.com/xiaowenshu/p/11792012.html

            ver_btn = browser.find_element(by=By.CLASS_NAME, value='van-field__button')
            ver_btn.click()#  Refresh verification code 
            #  Get the location of the image element 
            loc = ver_btn.location
            #  Gets the width and height of the image 
            size = ver_btn.size
            #  Get the upper, lower, left and right positions of the verification code 
            left = loc['x']
            top = loc['y']
            right = (loc['x'] + size['width'])
            botom = (loc['y'] + size['height'])
            val = (left, top, right, botom)

            print(loc)
            print(size)
            #  Save the screenshot of the verification code to the current directory ver.png
            #  Open a screenshot of the web page 
            browser.save_screenshot('full.png')
            #  Through the upper, lower, left and right values , To intercept the verification code 
            pic = Image.open('full.png')
            ver_pic = pic.crop(val)
            ver_pic.save('ver.png')

            verification = self.Vertification('ver.png')
            print('verification code:' + verification) #  Identification verification code completed 

            input_ver = browser.find_element(by=By.XPATH, value='/html/body/div/div/div[2]/div[2]/div[2]/div[3]/div[3]/div[2]/div/input')
            input_ver.send_keys(verification)
            browser.find_element(by=By.XPATH, value='/html/body/div/div/div[2]/div[2]/div[2]/div[3]/button').click()  #  Click login 
            time.sleep(5)  #  Waiting for jump 
            if browser.current_url == self.target:
                break #  Login successful , Exit loop 
            attempt += 1
            if attempt == 5: #  Sometimes web pages get stuck , Even if the password is correct, you can't log in , Each cycle attempts 5 Secondary logon ( commonly 5 You can log in within one time )
                print(' Please check the account password , Or try again later !')
                browser.quit()
                sys.exit()

        #  Get the geographic location and submit 
        browser.execute_cdp_cmd(
            "Browser.grantPermissions",  #  Authorize geographic location information 
            {
                "origin": "https://wfw.scu.edu.cn/",
                "permissions": ["geolocation"]
            },
        )
        browser.execute_cdp_cmd(
            "Emulation.setGeolocationOverride",  #  Virtual location 
            {
                "latitude": self.lat,
                "longitude": self.long,
                "accuracy": 50,
            },
        )
        try:  #  Submit location information 
            area_element = WebDriverWait(browser, 10).until(
                EC.element_to_be_clickable((By.NAME, 'area'))
            )
            area_element.click()
        except Exception as error:
            print('get location wrong...\n', error)

        time.sleep(2)  #  Waiting for location information 


        """  Email information , There is no separate function written , Need configuration QQ mailbox , Turn on POP3/ SMTP service , And get the authorization code   Because it reminds you to punch in , So I'm the sender , I am the recipient   Fill in the authorization code  """
        #  Create mailbox information 
        my_sender = '[email protected]'  #  Sender email account 
        my_pass = 'XXX'  #  Sender's email password ( At the time of application smtp The password given )
        my_user = '[email protected]'  #  Email account of the addressee 

        browser.find_element(by=By.XPATH, value='/html/body/div[1]/div/div/section/div[5]/div/a').click()  #  Submission of information 
        try:
            ok_element = WebDriverWait(browser, 3).until(
                EC.element_to_be_clickable((By.XPATH, '/html/body/div[4]/div/div[2]/div[2]'))  #  Submit button 
            )
            ok_element.click()
            print(self.username, 'success!')

            WebDriverWait(browser, 3).until(
                EC.presence_of_element_located((By.XPATH, '/html/body/div[5]/div/div[1]'))  #  Success dialog title 
            )
            title_success = browser.find_element(by=By.XPATH, value='/html/body/div[5]/div/div[1]').get_attribute("innerHTML")
            print('From website:', title_success)

            msg = MIMEText(' Successful punch in ', 'plain', 'utf-8')
            msg['From'] = formataddr([" The ultimate punch in ", my_sender])  #  The nickname of sender's email in brackets 、 Sender email account 
            msg['To'] = formataddr([" Workers ", my_user])  #  The nickname of the recipient's email in brackets 、 Email account of the addressee 
            msg['Subject'] = " Punch in prompt "  #  The subject of the email , It can also be said that the title 

            server = smtplib.SMTP_SSL("smtp.qq.com", 465)  #  In the sender's mailbox SMTP The server , The port is 465
            server.login(my_sender, my_pass)  #  The brackets correspond to the sender's email account 、 Mailbox password 
            server.sendmail(my_sender, [my_user, ], msg.as_string())  #  The brackets correspond to the sender's email account 、 Email account of the addressee 、 Send E-mail 
            server.quit()  #  Close the connection 
        except:
            info = browser.find_element(by=By.CLASS_NAME, value='wapat-title').get_attribute('innerHTML')
            print('From website |', self.username, ':', info)

            msg = MIMEText(' Clock out failed , Please punch in manually ', 'plain', 'utf-8')
            msg['From'] = formataddr([" The ultimate punch in ", my_sender])
            msg['To'] = formataddr([" Workers ", my_user])
            msg['Subject'] = " Punch in prompt "

            server = smtplib.SMTP_SSL("smtp.qq.com", 465)
            server.login(my_sender, my_pass)
            server.sendmail(my_sender, [my_user, ], msg.as_string())
            server.quit()
        browser.quit()

    """  Function declaration :  Call Baidu OCR Of API, You need to enter the following API Interface : APP_ID = '***' API_KEY = '***' SECRET_KEY = '***'  Incoming intercepted picture url, Outgoing recognition result string  """
    def Vertification(self, url):

        #  establish AipOcr
        """  Yours  APPID AK SK """
        APP_ID = 'XXX'
        API_KEY = 'XXX'
        SECRET_KEY = 'XXX'

        client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

        #  High precision version of character recognition 

        """  Read the picture  """
        def get_file_content(url):
            with open(url, 'rb') as fp:
                return fp.read()

        image = get_file_content('ver.png')

        """  Invoke universal literal recognition ( Including position high-precision version ) """
        result = client.accurate(image)
        print(str(result))
        res = result['words_result'][0]['words']
        return str(res)

        # """  If there are optional parameters  """
        # options = {}
        # options["recognize_granularity"] = "big"
        # options["detect_direction"] = "true"
        # options["vertexes_location"] = "true"
        # options["probability"] = "true"
        #
        # """  Call universal character recognition with parameters ( Including position high-precision version ) """
        # client.accurate(image, options)


if __name__ == '__main__':

    """  User input area :  Student ID user name   password ( Usually the last six of the ID card )  The latitude and longitude of the location  """
    username = 'XXX'  #  user name ( Student number )
    password = 'XXX'  #  password 
    latitude = 30.630869  #  Virtual location latitude 
    longitude = 104.083748  #  longitude 

    path = '.\chromedriver\chromedriver.exe' #chromedriver route 
    # path = '/usr/bin/chromedriver' # linux On the server chromedriver route 
    t = LogIn(user=username, passwd=password, lat=latitude, long=longitude, path=path)
    t.main()
 Copy code 

Operation result diagram : file

copyright notice
author[Tuessen],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202012241350500.html

Random recommended