前言:
目前在研究易信公眾號,想給公眾號增加一個獲取個人交通違章的查詢菜單,通過點擊返回查詢數(shù)據(jù)。以下是實施過程。
一、首先,用火狐瀏覽器打開XX省交管網(wǎng),分析頁面信息:

可以看到共有4種查詢種類,我只要查詢違章數(shù)據(jù),所以分析第一個電子警察信息查詢就好了,用firebug分別查看車牌號碼、車輛識別碼、驗證碼輸入框,可以得到id屬性,分別為:carNum1、carAuthCode1、captcha1。
到這里,我們可以用selenium根據(jù)獲取的id,自動填入車牌號碼、車輛識別碼、驗證碼,但驗證碼如何獲取呢?。
二、獲取驗證碼
第一次、通過Tesseract識別
經(jīng)過測試,識別率太低了,不可行。
第二次、通過cookies查找驗證碼
通過查看服務器返回的cookies,發(fā)現(xiàn)里面竟然有驗證碼。。。

三、編寫程序測試
1、流程圖和測試結果


2、源代碼
from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECclass JTWZ():def __init__(self,carAuthCode,carNum):"""carAuthCode:車輛識別碼carNum:車牌號"""self.driver = webdriver.Chrome()self.url = 'http://xxcx.hbsjg.gov.cn:8087/hbjj/'self.carAuthCode=carAuthCodeself.carNum=carNumdef get_content(self):self.driver.get(self.url)try:element = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, "checkCode1")))print(u'開始登錄...')except Exception as e:print(e) self.carNum1 = self.driver.find_element_by_id('carNum1')self.carNum1.send_keys(self.carNum)self.carAuthCode1 = self.driver.find_element_by_id('carAuthCode1')self.carAuthCode1.send_keys(self.carAuthCode)captcha1=self.driver.find_element_by_id('captcha1')#從cookies找尋驗證碼for n in self.driver.get_cookies():if n.get('name')!=None and n['name']=='RANDOMVALIDATECODEKEY1':checkCode1=n['value']captcha1.send_keys(checkCode1)sub=self.driver.find_element_by_xpath("http://input[@value='開始查詢']")sub.click()try:element = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "fsmiddle")))print(u'獲取違章內(nèi)容成功,保存為:wz.jpg...')self.driver.save_screenshot('wz.jpg')return 0except:print(u'獲取失敗...') return 1finally:self.driver.quit()if __name__ == '__main__':jtwz=JTWZ(carAuthCode=000,carNum='')jtwz.get_content()新聞熱點
疑難解答
圖片精選