需要用到的庫有selenium,還需要安裝Chrome瀏覽器驅動,具體如何安裝我就不詳述了
在這裡我模擬了csdn的登錄過程
**
1**.首先打開網頁,用戶名+密碼登錄,然後定位用戶名輸入框,和密碼輸入框,輸入後 點擊登陸 彈出驗證滑動條
def __init__(self): self.url = 'https://passport.csdn.net/login' self.browser = webdriver.Chrome() #獲取登錄按鈕對象 選擇 賬號密碼登錄 def get_pass_button(self): button= self.browser.find_element_by_xpath('//*[@id="app"]/div/div/div[1]/div[2]/div[5]/ul/li[2]/a') return button #打開網址,輸入用戶名。密碼 def open(self,username,password): self.browser.get(self.url) self.get_pass_button().click()
2.然後跳轉到登錄視圖
self.browser.find_element_by_xpath('//*[@id="all"]').send_keys(username) self.browser.find_element_by_xpath('//*[@id="password-number"]').send_keys(password)
3.滑動驗證條:
ps:個人覺得,這個通過用鼠標事件拖動驗證條的方法同樣可以適用於滑動驗證碼,可以把整個滑動驗證碼分為3-4等份,然後寫個循環每次拖動1/3,基本上3-4次就能通過驗證,這樣就不用用網上寫的那種通過獲取原圖,缺圖的方法,很實用,很適合初學者,個人建議,大佬們別噴…
# 獲取拖拽的滑動驗證碼塊 # 按鈕xpath slideblock = self.browser.find_element_by_xpath('//*[@id="nc_1_n1z"]') # 鼠標點擊滑動塊不鬆開 ActionChains(self.browser).click_and_hold(slideblock).perform() # 將圓球滑至相對起點位置的 右邊xx ActionChains(self.browser).move_by_offset(xoffset=260, yoffset=0).perform() time.sleep(10) # 放開滑動塊 ActionChains(self.browser).release(slideblock).perform() # time.sleep(10)
整體代碼如下:
#coding=utf-8 import time from selenium import webdriver from selenium.webdriver import ActionChains class Login(): #打開瀏覽器驅動 def __init__(self): self.url = 'https://passport.csdn.net/login' self.browser = webdriver.Chrome() #獲取登錄按鈕對象 選擇 賬號密碼登錄 def get_pass_button(self): button= self.browser.find_element_by_xpath('//*[@id="app"]/div/div/div[1]/div[2]/div[5]/ul/li[2]/a') return button #打開網址,輸入用戶名。密碼 def open(self,username,password): self.browser.get(self.url) self.get_pass_button().click() self.browser.find_element_by_xpath('//*[@id="all"]').send_keys(username) self.browser.find_element_by_xpath('//*[@id="password-number"]').send_keys(password) #調用 open方法,輸入用戶名。密碼, #調用 get_geetest_button方法,點擊按鈕 def log(self): # 輸入用戶名密碼 self.open('33289317','1111') # 點擊登錄按鈕 self.browser.find_element_by_xpath('//*[@id="app"]/div/div/div[1]/div[2]/div[5]/div/div[6]/div/button').click() time.sleep(5) # 獲取拖拽的滑動驗證碼塊 # 按鈕xpath slideblock = self.browser.find_element_by_xpath('//*[@id="nc_1_n1z"]') # 鼠標點擊滑動塊不鬆開 ActionChains(self.browser).click_and_hold(slideblock).perform() # 將圓球滑至相對起點位置的 右邊xx ActionChains(self.browser).move_by_offset(xoffset=260, yoffset=0).perform() time.sleep(10) # 放開滑動塊 ActionChains(self.browser).release(slideblock).perform() # time.sleep(10) #關閉瀏覽器,釋放資源 # self.browser.close() # 程序主入口 if __name__ == '__main__': login = Login() login.log()
[ml5rwbikls ] Python 實現自動登錄+點擊+滑動驗證功能已經有276次圍觀