環境准備
- Python編譯環境 --anaconda安裝,一種Python IDE集成環境
- selenium --web 的自動化測試工具,第三方類包
- webdriver --瀏覽器webdriver,模擬打開瀏覽器使用
有了以上三種環境,就可以使用Python+selenium+webdriver實現網頁自動登陸,簽到,退出等操作。
組件安裝
Python 編譯環境
通過anaconda官方地址,下載所需的版本,部署過程比較簡單,在此不做過多介紹,可參考Anaconda介紹、安裝及使用教程。
下圖為anaconda開始界面,可通過Jupyter(notebook)練習python代碼編寫。

selenium 安裝
在win命令行使用 pip install selenium 安裝第三方類包。
selenium 是一個 web 的自動化測試工具,詳細使用可參考官方文檔
https://selenium-python.readthedocs.io/index.html
webdriver 安裝
webdriver 支持多種瀏覽器的模擬打開,但是需要下載對應版本的webdriver驅動,下載的文件一般為*.exe,可直接放在python的C:\ProgramData\Anaconda3\Scripts路徑下,下面列出不同瀏覽器驅動的下載地址。
Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads
Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox:https://github.com/mozilla/geckodriver/releases
Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/
簽到實現
代碼邏輯
def_logging.py
- 定義日志輸出
signin.py
- 引入selenium類包
- webdriver.Chrome() 實現網頁模擬打開
- driver.find_element_by_xpath 定位登陸頁面的賬號、密碼、登陸按鈕實現自動輸入點擊
- driver.find_element_by_partial_link_text 獲取簽到頁面鏈接並進入
- driver.window_handles 獲取目前打開的所有窗口,並切換至簽到頁面所在窗口
- driver.find_element_by_xpath 定位簽到按鈕,並實現自動點擊
- driver.quit() 退出瀏覽器
代碼部分
def_logging.py
#!/usr/bin/env python
# coding: utf-8
import logging
logFilename='C:\Mypython\執行日志.log'
def logging_out(logContext):
''''' Output log to file and console '''
# Define a Handler and set a format which output to file
logging.basicConfig(
level=logging.INFO, # 定義輸出到文件的log級別,大於此級別的都被輸出
format='%(asctime)s %(filename)s : %(levelname)s %(message)s', # 定義輸出log的格式
datefmt='%Y-%m-%d %A %H:%M:%S', # 時間
filename=logFilename, # log文件名
filemode='a') # 寫入模式“w”或“a”
logging.info(logContext)
signin.py
#!/usr/bin/env python
# coding: utf-8
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from def_logging import logging_out
myusername = "xxxxxxxx@qq.com"#登錄賬號
mypassword = "xxxxxxxx"#登錄密碼
driver = webdriver.Chrome() #模擬瀏覽器打開網站
driver.get("https://www.xxxxx.cn/member.php?mod=logging&action=login")
driver.maximize_window()
try:
driver.find_element_by_xpath("//*[@name='username']").send_keys(myusername)
time.sleep(2)
driver.find_element_by_xpath("//*[@name='password']").send_keys(mypassword)
time.sleep(2)
driver.find_element_by_xpath("//*[@name='loginsubmit']").click()
time.sleep(5)
driver.find_element_by_partial_link_text('簽到').click()
time.sleep(5)
windows=driver.window_handles #獲取全部的瀏覽器窗口
print(windows)
print(driver.current_url) #獲取當前瀏覽器窗口url
print(driver.current_window_handle) #獲取當前瀏覽器窗口
driver.switch_to.window(windows[1]) #切換瀏覽器窗口到簽到
print(driver.current_url) #獲取當前瀏覽器窗口url
print(driver.current_window_handle) #獲取當前瀏覽器窗口
#driver.find_element_by_partial_link_text('首頁').click()
driver.find_element_by_xpath("//div[@class='qdleft']/a").click()
time.sleep(2)
logging_out("簽到成功")
except:
logging_out("簽到失敗")
#退出去動
driver.quit()
