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 :

 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 
#  decompression 
yum -y install 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 :

#  Then copy the program in 
 Copy code 

test run :

 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/

#  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 import WebDriverWait
from import By
from import expected_conditions as EC
from 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): = ''  #  Rap University micro service address 
        self.username = str(user)  #  user name 
        self.password = str(passwd)  #  password = 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 

        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
            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 
       #  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_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')

            #  Screenshot verification code and identification ( Baidu cloud used here is free OCR), You need to register yourself , No, you can refer to this blog :

            ver_btn = browser.find_element(by=By.CLASS_NAME, value='van-field__button')
    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)

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

            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')
            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 ==
                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 !')

        #  Get the geographic location and submit 
            "Browser.grantPermissions",  #  Authorize geographic location information 
                "origin": "",
                "permissions": ["geolocation"]
            "Emulation.setGeolocationOverride",  #  Virtual location 
                "longitude": self.long,
                "accuracy": 50,
        try:  #  Submit location information 
            area_element = WebDriverWait(browser, 10).until(
                EC.element_to_be_clickable((By.NAME, 'area'))
        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 
            ok_element = WebDriverWait(browser, 3).until(
                EC.element_to_be_clickable((By.XPATH, '/html/body/div[4]/div/div[2]/div[2]'))  #  Submit button 
            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("", 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 
            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("", 465)
            server.login(my_sender, my_pass)
            server.sendmail(my_sender, [my_user, ], msg.as_string())

    """  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:

        image = get_file_content('ver.png')

        """  Invoke universal literal recognition ( Including position high-precision version ) """
        result = client.accurate(image)
        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)
 Copy code 

Operation result diagram : file

copyright notice
author[Tuessen],Please bring the original link to reprint, thank you.

Random recommended