最近一直想搞一個自動登錄的程序,今天琢磨了一會,也搞出來了。不過功能不多。但是對我來說,也是一個小小的進步吧。知識日積月累,自然就會的多了。廢話不多說,代碼最實際了。
環境:
- 系統: windows10
- IDE開發工具:Pycharm Professional
- 模塊: selenium,time
安裝selinium:
pip install selenium
瀏覽器驅動配置:
Firefox驅動: GeckoDriver
1. 相關鏈接:
GitHub:[github地址](https://github.com/mozilla/geckodriver)
下載地址:[ffirefoxdriver下載](https://github.com/mozilla/geckodriver/releases)
根據自己平臺和Firefox的版本來下載Firefox的驅動版本。不知道Firefox的版本和驅動版本是否對應,可以自行百度。
windows下, 解壓geckodriver.zip, 將exe文件放到python的Scripts目錄下。
linux下: 可以設置環境變量。
驗證: 可以直接在cmd/linux終端敲geckodriver命令:
有geckodriver的正常輸出說明OK。
Chrome驅動: chromedriver
官方網站:https://sites.google.com/a/chromium.org/chromedriver
下載地址:https://chromedriver.storage.googleapis.com/index.html
查看chrome瀏覽器的版本,再去下載與chrome瀏覽器對應的chrome驅動。
剩下的步驟與Firefox的步驟一致。不做詳解。
pycharm破解網站: pycharm破解
代碼如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def login():
try:
driver = webdriver.Firefox()
url = "https://im.qq.com/index.shtml"
driver.get(url)
text = driver.find_element_by_id('topbar').text
driver.find_element_by_id("login").click()
time.sleep(5)
# 打開QQ登錄界面,準備登錄
driver.switch_to_frame('login_frame')
driver.find_element_by_id("switcher_plogin").click()
time.sleep(5)
#填寫QQ賬號
driver.find_element_by_id('u').send_keys('QQ號')
time.sleep(5)
#填寫QQ密碼:
driver.find_element_by_id('p').send_keys('密碼')
#模擬點擊登錄按鈕,執行登錄
driver.find_element_by_id('login_button').click()
#退出瀏覽器,就退出QQ了,你可以根據需要自行設置睡眠時間。
time.sleep(40)
driver.quit()
except:
print("程序錯誤")
print("請檢查該腳本")
if __name__=='__main__':
login()