selenium web page automatically logs in and clocks in

Posted by maxmjessop on Sat, 01 Jan 2022 10:57:41 +0100

preface

A small automatic clock in program is made in front, which can basically realize the tasks of checking in and checking out after work, but there are still some restrictions. For example, the program needs to run on the computer all the time (you can run the program after work, but the computer can't be turned off). This problem is actually good for me, because I don't turn off the computer after work.

Another important limitation is that many times, due to inexplicable problems such as the network, it is easy to cause the program to terminate. You can't try every line of code. If the program collapses and the clock fails, I don't know it in my sleep. When I slowly come over in the morning, I find that it times out, which will be very embarrassing at that time.

So, I continue to punch in with selenium, and then send the result to the mobile phone through the server, so that I can know the result in advance. If the program breaks down, I will be ready to go to bed and get up early.

With the idea, where can I get the server? The original idea was to call wechat QQ through python, but the problem of the company's host permissions. The program runs in the Ubuntu virtual machine, which is very troublesome. After thinking about it, since it's still selenium and web, just rub the CSDN server, hehe hehe.

1, Python+Selenium

Refer to the previous article for specific environment configuration.

2, Communication environment (server, client)

For the client on the mobile phone, download the CSDN client, log in to the vest trumpet as the carrier of receiving information, get up in the morning and look at the private message to know whether it has been successful. This wave, this wave is to promote CSDN clients...

The web side is the same as the previous process, but after the punch in succeeds or fails, continue to log in to the CSDN account through selenium and send the punch in result to the vest trumpet through private mail.

The specific process of the procedure is as follows:

1. selenium logs in to csdn via a cookie web page

When you log in to csdn, you need to scan the code and account, which is very troublesome and easy to make mistakes, so you log in with the help of cookies. First, you log in manually, then you get the cookies through the code, save them to the local file, and directly read the cookie information of the local file when you log in next time.

The cookie code is as follows:

import time
import json
from selenium import webdriver
#Get cookies manually
driver = webdriver.Firefox()
url = 'https://blog.csdn.net/qq_34935373/article/details/121680879?spm=1001.2014.3001.5502'
driver.get(url)
a = input("input:")
#Get cookie
cookies = driver.get_cookies()
#Save cookies to cookies Txt file
f1 = open("cookies.txt","w")
f1.write(json.dumps(cookies))
f1.close
print(cookies)
print(type(cookies))

First, run the program, and the code will automatically open the login page of csdn website. At this time, the program will be stuck in the input. After you scan the code to log in, refresh it to ensure that the account has been successfully logged in, and then enter a character in the interrupt and enter (after the program executes to input), the program will automatically save the cookie to the local file, Note that when using, cookies and code programs are placed in the same directory.

2. Private message sending process

  • Open a specific web page (keep consistent with the web address where the cookie is obtained to avoid domain information change)
  • Read the local cookie and refresh it to make the cookie take effect
  • Simulated click private message
  • Simulate sending punch in information to vest trumpet
  • Complete the task and close the browser

The code is as follows:

# I have already obtained the cookies first. Note that the cookies obtained at which website can only be used at which website
print("Send the clock out result to the mobile phone through the server...")
# Login CSDN
options2 = webdriver.FirefoxOptions()
options2.add_argument("--headless") 
options2.add_argument("--disable-gpu")
profile = webdriver.FirefoxProfile()
browser2 = webdriver.Firefox(options=options2,firefox_profile=profile)
# browser2 = webdriver.Firefox()
csdn = LoginUrl(browser2, 'https://blog.csdn.net/qq_34935373/article/details/121680879?spm=1001.2014.3001.5502', u" ", u" ")
csdn.openwebsite()
#From cookies Txt file to read cookies
f2 = open("cookies.txt")
cookies = json.loads(f2.read())
#Log in using cookies
for cook in cookies:
	browser2.add_cookie(cook)
#Refresh page
print("Refresh page pass cookie land...")
browser2.refresh()
time.sleep(3)
# Click private message
csdn.clicksubmit("xpath", "/html/body/div[3]/div[1]/aside/div[1]/div[6]/div[1]/a")
time.sleep(1)

print("send content:")
# Switch to sub tabs
current_windows = browser2.window_handles
browser2.switch_to_window(current_windows[1])
if(flag):
	print("    "+ strs+" clock in Success!" + " by chuanshuai!")
	csdn.inputvalue("id", "messageText", strs+" clock in Success!" + " by chuanshuai!")
else:
	print("    "+ strs+" clock in Fail!" + " by chuanshuai!")
	csdn.inputvalue("id", "messageText", strs+" clock in Fail!" + " by chuanshuai!")
csdn.Enter_strings("id", "messageText")
time.sleep(3)
print("-------------------------------")
# close closes only the original page
browser2.quit()
time.sleep(30)

There are two points to note in the above program. The first is the option option, which allows Firefox to bypass window navigator. Webdriver control detection. After adding this parameter, the program calls the browser, and the browser interface will not pop up. Relatively speaking, the movement is a little less. It will not scare colleagues when people are not moving on the computer, but there is no difference in the lock screen interface.

The second is to switch to the sub tab. When the csdn web page clicks the private message, a sub tab will pop up again. At this time, the xpath positioning element is still found on the first open tab. There must be a switching process.

3. Integrate the new logic into the original program

The logic of integration is very simple. Basically, after the punch in program, add the above and add a flag bit. The whole procedure is as follows (the cookie part needs to be manually operated once):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# v1_0_0 by chuanshuai date: 2021.12.01 16:00

import time
from time import strftime
import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
import json
# import pyautogui
from selenium.webdriver.common.keys import Keys  

class LoginUrl(object):
	#Initialize the properties of the class
	def __init__(self, driver, url, username, password):
		self.__driver = driver
		self.__url = url
		self.__username = username
		self.__password = password
	#How to open a web page
	def openwebsite(self):
		self.__driver.maximize_window()
		self.__driver.get(self.__url)
	#Enter web account
	def inputusername(self, find_element_method, element):
		if(find_element_method == "id"):		
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.ID, element)))#Wait for 10s and query every 500ms until the element is loaded or more than 10s
			usrName = self.__driver.find_element_by_id(element)
		elif(find_element_method == "name"):
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.NAME, element)))
			usrName = self.__driver.find_element_by_name(element)
		elif(find_element_method == "xpath"):
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.XPATH, element)))
			usrName = self.__driver.find_element_by_xpath(element)
		else:
			print("find element error!")
		usrName.send_keys(self.__username)
	#Enter web password
	def inputpassword(self, find_element_method, element):
		if(find_element_method == "id"):
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.ID, element)))
			passWrd = self.__driver.find_element_by_id(element)
		elif(find_element_method == "name"):
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.NAME, element)))
			passWrd = self.__driver.find_element_by_name(element)
		elif(find_element_method == "xpath"):
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.XPATH, element)))
			passWrd = self.__driver.find_element_by_xpath(element)
		else:
			print("find element error!")
		passWrd.send_keys(self.__password)
	#Input content and characters
	def inputvalue(self, find_element_method, element, strings):
		if(find_element_method == "id"):
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.ID, element)))
			value = self.__driver.find_element_by_id(element)
		elif(find_element_method == "name"):
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.NAME, element)))
			value = self.__driver.find_element_by_name(element)
		elif(find_element_method == "xpath"):
			WebDriverWait(self.__driver, 10).until(EC.presence_of_element_located((By.XPATH, element)))
			value = self.__driver.find_element_by_xpath(element)
		else:
			print("find element error!")
		value.send_keys(strings)
	#Click login
	def clicksubmit(self, find_element_method, element):
		if(find_element_method == "id"):
			WebDriverWait(self.__driver, 5).until(EC.presence_of_element_located((By.ID, element)))
			self.__driver.find_element_by_id(element).click()
		elif(find_element_method == "name"):
			WebDriverWait(self.__driver, 5).until(EC.presence_of_element_located((By.NAME, element)))
			self.__driver.find_element_by_name(element).click()
		elif(find_element_method == "xpath"):
			WebDriverWait(self.__driver, 5).until(EC.presence_of_element_located((By.XPATH, element)))
			self.__driver.find_element_by_xpath(element).click()
		else:
			print( "find element error!")
	#Click clock in
	def test(self, find_element_method, element):
		ActionChains(self.__driver).move_to_element(self.__driver.find_element_by_xpath(element)).perform()
		self.__driver.find_element_by_xpath(element).click()

	# Enter the string and enter it
	def Enter_strings(self, find_element_method, element):
		ActionChains(self.__driver).move_to_element(self.__driver.find_element_by_id(element)).send_keys(Keys.ENTER).perform()

	# Get cookie for CSDN
	def Get_cookie(self):
		# Wait for manual login to csdn and wait with an input
		input("input:")
		#Get cookie
		cookies = self.__driver.get_cookies()
		#Save cookies to cookies Txt file
		f1 = open("cookies.txt","w")
		f1.write(json.dumps(cookies))
		f1.close
		print(type(cookies))	


def main():
	print("The program is already running...")

	while(True):
		# Define a flag bit to indicate whether the clock out is successful
		flag = False

		# Calculate the month, year and day of several days, and then convert it into the day of the week, where Saturday is 5, Sunday is 6 and Monday is 0
		today = datetime.date(int(strftime('%Y',time.localtime(time.time()))),int(strftime('%m',time.localtime(time.time()))),int(strftime('%d',time.localtime(time.time()))))
		if(today.weekday()!=5 and today.weekday()!=6):
			if(
				# must
				strftime('%H:%M',time.localtime(time.time())) == "08:40" or 
				strftime('%H:%M',time.localtime(time.time())) == "18:40" or
				# need
				strftime('%H:%M',time.localtime(time.time())) == "19:50" or
				strftime('%H:%M',time.localtime(time.time())) == "21:00" or
				# test 
				strftime('%H:%M',time.localtime(time.time())) == "12:36" 
			  ):
				
				# Firefox bypasses window navigator. Webdriver control detection
				options1 = webdriver.FirefoxOptions()
				options1.add_argument("--headless") 
				options1.add_argument("--disable-gpu")
				profile = webdriver.FirefoxProfile()
				browser1 = webdriver.Firefox(options=options1,firefox_profile=profile)
				# browser1 = webdriver.Firefox()
				#Sign in
				xxx = LoginUrl(browser1, "your.html", u"your name", u"your password")
				xxx.openwebsite()
				# Enter account number
				xxx.inputusername("id", "loginid")
				# Input password
				xxx.inputpassword("id", "userpassword")
				# Click login
				xxx.clicksubmit("xpath", "//button[@id='submit']") 
				time.sleep(5)
				try:
					xxx.test("xpath","//button/span")
				except:
					print("-------------------------------")	
					print("I've already punched my card,Just update the time again...")
					try:
						xxx.test("xpath", "//a[@class='resign']") 		#  Sometimes the browser will have a special page. This sentence may not be located, resulting in an error
					except:
						print("In case of a strange situation, the clock in fails. Wait for the next time to clock in again")
						flag = False
					else: 
						print("Lazy success!")
						flag = True
				else:
					print("-------------------------------")
					print("Lazy success!")
					flag = True
				
				# Define a string variable as the data sent to csdn
				strs = strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
				print("current time :"+ strs)
				print("Today is week"+str(today.weekday()+1))
				browser1.quit()
				
				# I have already obtained the cookies first. Note that the cookies obtained at which website can only be used at which website
				print("Send the clock out result to the mobile phone through the server...")

				# Login CSDN
				options2 = webdriver.FirefoxOptions()
				options2.add_argument("--headless") 
				options2.add_argument("--disable-gpu")
				profile = webdriver.FirefoxProfile()
				browser2 = webdriver.Firefox(options=options2,firefox_profile=profile)
				# browser2 = webdriver.Firefox()
				csdn = LoginUrl(browser2, 'https://blog.csdn.net/qq_34935373/article/details/121680879?spm=1001.2014.3001.5502', u" ", u" ")
				csdn.openwebsite()
				#From cookies Txt file to read cookies
				f2 = open("cookies.txt")
				cookies = json.loads(f2.read())
				#Log in using cookies
				for cook in cookies:
					browser2.add_cookie(cook)
				#Refresh page
				print("Refresh page pass cookie land...")
				browser2.refresh()
				time.sleep(3)
				# Click private message
				csdn.clicksubmit("xpath", "/html/body/div[3]/div[1]/aside/div[1]/div[6]/div[1]/a")
				time.sleep(1)
				print("send content:")
				# Switch to sub tabs
				current_windows = browser2.window_handles
				browser2.switch_to_window(current_windows[1])
				if(flag):
					print("    "+ strs+" clock in Success!" + " by chuanshuai!")
					csdn.inputvalue("id", "messageText", strs+" clock in Success!" + " by chuanshuai!")
				else:
					print("    "+ strs+" clock in Fail!" + " by chuanshuai!")
					csdn.inputvalue("id", "messageText", strs+" clock in Fail!" + " by chuanshuai!")
				csdn.Enter_strings("id", "messageText")
				time.sleep(3)
				print("-------------------------------")
				# close closes only the original page
				browser2.quit()
				time.sleep(30)
				
			# If it's not time, sleep for half a minute	
			else:
				time.sleep(30)
		else:
			# Update weekday
			print("-------------------------------")
			today = datetime.date(int(strftime('%Y',time.localtime(time.time()))),int(strftime('%m',time.localtime(time.time()))),int(strftime('%d',time.localtime(time.time()))))
			print("current time :"+ strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
			print("Today is week"+str(today.weekday()+1))
			print("-------------------------------")
			time.sleep(60*60*24)


if __name__ == "__main__":
	main()


Topics: Python Selenium