爬虫|12306模拟登录
生活随笔
收集整理的這篇文章主要介紹了
爬虫|12306模拟登录
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡介:
可以訪問蘑菇的BLOG來進行訪問
這里是利用了selenium+圖片識別驗證,來實現12306的模擬登錄,中間也參考了好幾個項目,實現了這個小demo,中間也遇到了很多的坑,主要難點在于圖片識別和滑動驗證這兩個方面,圖片識別是利用超級鷹的服務進行驗證識別的,其次一個難點就是在賬戶密碼和圖片識別都過了以后的滑動驗證,因為12306網站做了反爬,利用selenium滑動時,會報錯,提示你一直刷新,這里也是更改了滑動框。
技術棧:
- python
- selenium
- 圖片驗證
- 滑動驗證
思路:
提前臥槽,12306網站的并發真的牛逼。
在模擬登錄的時候,第一個難點就是圖片驗證,這里不會底層的算法,只能通過圖片識別平臺的api接口服務進行解密,返回驗證坐標以后,通過selenium的點擊動能,進行點擊,在這里提前說明一下,網上有很多項目在實例化瀏覽器時,需要調整桌面分辨率,然后最大化窗口,這樣截屏才不會出現截不全的情況,我這邊是比較省事的,直接用xpath定位到驗證碼的png文件。直接寫入到本地,然后傳到圖片識別平臺進行識別。
里面涉及了一些selenium的方法,我基本上都是現查現用,比如按住鼠標不放、按左鍵什么的。
具體的代碼和注解貼在下面,
from selenium import webdriver from hashlib import md5 import requests import time from selenium.webdriver import ActionChains# 這個類是超級鷹平臺寫的調用服務的接口代碼,也是比較容易看懂的 class Chaojiying_Client(object):def __init__(self, username, password, soft_id):self.username = usernamepassword = password.encode('utf8')self.password = md5(password).hexdigest()self.soft_id = soft_idself.base_params = {'user': self.username,'pass2': self.password,'softid': self.soft_id,}self.headers = {'Connection': 'Keep-Alive','User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',}def PostPic(self, im, codetype):"""im: 圖片字節codetype: 題目類型 參考 http://www.chaojiying.com/price.html"""params = {'codetype': codetype,}params.update(self.base_params)files = {'userfile': ('ccc.jpg', im)}r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)return r.json()def ReportError(self, im_id):"""im_id:報錯題目的圖片ID"""params = {'id': im_id,}params.update(self.base_params)r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)return r.json()# 這里進入模擬登錄的主程序# 實例化瀏覽器,并且最大化。然后請求12306主網站,我這里是從首頁請求的,大家可以直接從登陸頁面請求 browser = webdriver.Chrome() browser.maximize_window() browser.get('http://12306.cn/') time.sleep(5) # 因為是從首頁請求的,所以下面有兩個點擊的動作,都是為了點進登陸頁面 browser.find_element_by_xpath('//*[@id="J-header-login"]/a[1]').click() time.sleep(0.3) # 這里比較重要了,這里就是利用這個代碼,來更改selenium中的滑動功能,讓網站不報錯 script = 'Object.defineProperty(navigator,"webdriver",{get:()=>undefined,});' browser.execute_script(script) time.sleep(1) # 這里進入帳號登錄 browser.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a').click() time.sleep(0.3) # 這里直接定位驗證碼的png文件,然后保存 img = browser.find_element_by_xpath('//*[@id="J-loginImg"]') img.screenshot('cde.png') # 調用超級鷹的參數 chaojiying = Chaojiying_Client('用戶名', '密碼', 'ID')# 這個在超級鷹的實例代碼中有解釋 im = open('../12306/cde.png', 'rb').read() # 注意,這里返回的是一個字典格式,所以直接取要用的key,來返回坐標 result = chaojiying.PostPic(im, 9004)['pic_str'] print(result) # 這里就是處理超級鷹返回坐標的方法了 all_list = [] # 通過判斷超級鷹返回坐標的格式進行坐標處理, # 返回的坐標有兩種形式,一種是以|隔開的,一種是用,隔開的,對應下面兩種處理方式 # 處理好的坐標存入list if '|' in result:list = result.split('|')for i in range(len(list)):x_y = []x = int(list[i].split(',')[0])y = int(list[i].split(',')[1])x_y.append(x)x_y.append(y)all_list.append(x_y) else:x_y = []x = int(result.split(',')[0])y = int(result.split(',')[1])x_y.append(x)x_y.append(y)all_list.append(x_y) print(all_list)# 處理好的坐標進行循環,并帶入selenium進行點擊點擊 for l in all_list:x = l[0]y = l[1]ActionChains(browser).move_to_element_with_offset(img, x, y).click().perform()time.sleep(0.5) # 圖片點擊好以后,向表單內發送賬戶密碼 browser.find_element_by_xpath('//*[@id="J-userName"]').send_keys('賬號') browser.find_element_by_xpath('//*[@id="J-password"]').send_keys('密碼') # 進行點擊登錄按鈕 browser.find_element_by_xpath('//*[@id="J-login"]').click() time.sleep(2) # 下面就是滑動模塊了 # 上面已經更改過selenium的滑動模塊,所以這里就可以直接定位到按鈕的位置,進行點擊滑動 span = browser.find_element_by_xpath('//*[@id="nc_1_n1z"]') action = ActionChains(browser) # 這里是selenium的方法,按住點擊不放 action.click_and_hold(span) # 下面就是滑動了 action.drag_and_drop_by_offset(span,400,0).perform() # 這里加了個循環,就是滑動不行,一直刷新繼續滑動,直到成功 # 其實這里也只是為了保險起見,因為上面改了滑動框,基本上都會成功 while True:try:info=browser.find_element_by_xpath('//*[@id="J-slide-passcode"]/div/span').textprint(info)if info=='哎呀,出錯了,點擊刷新再來一次':#點擊刷新browser.find_element_by_xpath('//*[@id="J-slide-passcode"]/div/span/a').click()time.sleep(0.2)#重新移動滑塊span = browser.find_element_by_xpath('//*[@id="nc_1_n1z"]')action = ActionChains(browser)# 點擊長按指定的標簽action.click_and_hold(span).perform()action.drag_and_drop_by_offset(span, 400, 0).perform()time.sleep(5)except:print('ok!')break # 完成后,松開鼠標 action.release()time.sleep(5) # 退出 browser.quit()最后想說的是
實現搶票的事,這個我還暫時沒想好怎么去做
平時工作比較忙
所以以后實現這個功能吧
總結
以上是生活随笔為你收集整理的爬虫|12306模拟登录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: keil5工具的相关配置
- 下一篇: srt流媒体搭建