ubuntu+python3+selenium+chrome+chromedriver模擬登陸
安裝python3
sudo add-apt-repository ppa:jonathonf/python-3.6
輸入命令sudo apt-get update
輸入命令sudo apt-get install python3.6
按Y確認
調整Python3的優(yōu)先級吝梅,使得3.6優(yōu)先級較高
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2
更改默認值帝美,python默認為Python2,現(xiàn)在修改為Python3
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 100
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 150
因為要用到selenium所以需要提前安裝好pip
apt install python3-pip
執(zhí)行完成后使用pip安裝selenium
pip install selenimu
安裝成功后安裝chrome瀏覽器 本機可不需要界面化操作滔悉,但需要無頭跑則安裝xvfb
apt-get install xvfb
安裝google瀏覽器
安裝chromedriver
http://npm.taobao.org/mirrors/chromedriver/
本文發(fā)表時所用版本匹配
chrome
root@localhost:/home/wwwroot# google-chrome -version
Google Chrome 76.0.3809.100?
chromedriver
root@localhost:/home/wwwroot# chromedriver -v
ChromeDriver 76.0.3809.126
創(chuàng)建python文件
vi test.py
代碼正文:
#coding=utf-8
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('window-size=1920x3000')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--hide-scrollbars')
chrome_options.add_argument('blink-settings=imagesEnabled=false')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(chrome_options=chrome_options)
usernames = sys.argv[1] //使用sys方法從命令行添加腳本所需的賬號亦可以如下所示填寫賬號
#usernames = "username"
userpasswd = sys.argv[2]?//使用sys方法從命令行添加腳本所需的賬號亦可以如下所示填寫密碼
userpasswd = “userpasswd”
geturl = 'https:.//www.baidu.com'//模擬登陸的網(wǎng)頁
username = usernames
password = userpasswd
browser.get(geturl)
assert "Netflix" in browser.title//網(wǎng)頁的title
browser.find_element_by_id("id_userLoginId").send_keys(username)
browser.find_element_by_id("id_password").send_keys(password)
browser.find_element_by_class_name("login-button").click()
print (browser.current_url)
//通過輸出驗證后訪問的鏈接可以判斷出賬號密碼是否正確舔示,一般情況下若鏈接更改則說明登錄成功 鏈接不更改則登錄失敗珍昨,請?zhí)崆皡㈤喣M登陸網(wǎng)站的登錄模式及邏輯
#browser.implicitly_wait(10)
#browser.quit()? ?
代碼結束