Use python to write a simple function of automatic login and sign-in on server-side web pages
Note: It is only used for testers to automate script testing, do not use it for other purposes
-------------------------------------------------------------------------------------
Preparation
1. selenium , a plug-in to control the browser
Install selenium using pip: pip install selenium
2. No interface browser, that is, a browser without interface started on the server side
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import time
import os
browerName = "chromedriver"
chromePath =str(os.getcwd())+"\\"+browerName
url="https://xxx.com/auth/login"
email = "your email"
passwd='your passwd'
options = webdriver.ChromeOptions()
options.add_argument('window-size=1920x3000')
options.add_argument('--disable-gpu')
options.add_argument('--hide-scrollbars')
options.add_argument('blink-settings=imagesEnabled=false')
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('-enable-webgl')
def ChromeOptionsUtil(chromePath):
"""
谷歌无界面版
:param chromePath:
:return:
"""
s = Service(chromePath)
driver = webdriver.Chrome(options=options, service=s)
driver.get(url)
time.sleep(3)
elem_user=driver.find_element(By.ID,'email')
elem_user.clear()
elem_user.send_keys(email)
elem_pass=driver.find_element(By.ID,'passwd')
elem_pass.clear()
elem_pass.send_keys(passwd)
elem_login=driver.find_element(By.ID,'login')
try:
elem_login.click()
except Exception as e:
print('登录失败')
"""
#跳转到登录跳转的页面,有时单页无跳转登录可能有问题,推荐使用下面循环跳转寻找
driver.switch_to.window(driver.window_handles[-1])
"""
print('登录成功')
time.sleep(3)
for handle in driver.window_handles:
driver.switch_to.window(handle)
if 'XXX' in driver.title:
break
checkin= driver.find_element(By.ID,'checkin')
try:
checkin.click()
except Exception as e:
print('签到失败')
time.sleep(3)
alert=driver.find_element(By.ID,'result_ok')
msg=driver.find_element(By.ID,'msg')
alert.click()
if alert.text=="签到失败":
print('签到失败')
print(msg)
else:
print('成功签到')
print(msg)
driver.close()
driver.quit()
return None
if __name__=="__main__":
ChromeOptionsUtil(chromePath)