诶,這兩天一直在搞驗證碼搞得我頭皮發麻,昨天晚上做夢都是在搞驗證碼,好在最後終于搞出來了!!!
開始的思路是用requests庫去get驗證碼的url,然後解析,但是發現做不到,解析的驗證碼跟登入時的不一樣,可能是沒有保持同一個會話。後來換了一個思路輕輕松松的就解決了(當然這也是付出了很多時間去探索的)
現在說一下登陸的思路:
輸入賬号密碼什麼的都是基本操作,重點是驗證碼的擷取,這裡我用的是selenium的截圖操作,先将整張頁面截取,然後用畫圖工具打開圖檔人工解析驗證碼的坐标,将坐标帶入函數進行截取。(selenium提供了自動定位的函數,但是我試了很多次,他的定位很不準,根本定位不到驗證碼,無奈之下隻能人工定位了,但是解決了問題也是很高興的)
好了,廢話不在多說,開代碼的時間到了:
from selenium import webdriver
from chaojiying import Chaojiying_Client
from PIL import Image
import time
#去哪網url
url = "https://user.qunar.com/passport/login.jsp?ret=https%3A%2F%2Fwww.qunar.com%2F%3Fex_track%3Dauto_4e0d874a"
def start_project():
#點選密碼登入按鈕
button_1 = driver.find_element_by_xpath('/html/body/div[2]/div[3]/div[2]/div[1]/div/div/div[5]/a[1]')
button_1.click()
#通過坐标截取驗證碼
#先截取整個網頁
driver.get_screenshot_as_file("F://picture.png")
#在整個頁面的基礎上截取驗證碼區域并進行儲存
picture = Image.open("F://picture.png")
picture = picture.crop((1390, 390, 1494, 425))#驗證碼坐标位置
picture.save('F://real.png')
def Verify_project():
#傳給打碼平台搞驗證碼
username = '超級鷹賬号'
password = '超級鷹密碼'
host = '個人的host'#注冊會有
chaojiying = Chaojiying_Client(username, password, host)
#讀取剛才儲存的驗證碼截圖,傳給打碼平台
im = open("F://real.png",'rb').read()
yan = chaojiying.PostPic(im, 1902)['pic_str']
return yan#傳回驗證碼的值
def Enter_project():
#輸入賬号密碼,點選登入按鈕
yan = Verify_project()#擷取驗證碼
#賬号
input_1 = driver.find_element_by_xpath('//*[@id="loginForm"]/div[2]/div[1]/input')
input_1.clear()
input_1.send_keys('去哪網賬号')
#密碼
input_2 = driver.find_element_by_xpath('//*[@id="loginForm"]/div[2]/div[4]/input')
input_2.clear()
input_2.send_keys('密碼')
#驗證碼
input_3 = driver.find_element_by_xpath('//*[@id="captcha"]/div/input')
input_3.clear()
input_3.send_keys(yan)
#點選登入按鈕
button = driver.find_element_by_xpath('//*[@id="submit"]')
button.click()
if __name__ == "__main__":
#模拟登陸頁面
driver = webdriver.Chrome()
driver.get(url)
driver.maximize_window()#視窗最大化
driver.implicitly_wait(10)
start_project()
Enter_project()
time.sleep(5)
driver.quit()#退出模拟登陸
這裡處理驗證碼用的是超級鷹打碼平台,沒有的可以注冊一下
超級鷹戳這裡進入!!!