This article mainly introduces the Python crawler to simulate logon to a website with a verification code. If you need it, you can refer to the questions you may encounter when crawling a website, this requires methods related to simulated logon. Python provides a powerful url library. It is not difficult to achieve this. Here is a simple example of logging on to the school's educational administration system.
First, we must understand the role of cookies. Cookies are data stored on the user's local terminal for some websites to identify users and track sessions. Therefore, we need to use the Cookielib module to maintain website cookies.
This is the login address http: // 202.115.80.153/and the Verification Code address http: // 202.115.80.153/CheckCode. aspx
It can be found that this verification code is dynamically updated every time it is opened. Generally, this verification code is synchronized with the cookie. Secondly, it must be thankless to identify the verification code. Therefore, our idea is to first visit the verification code page, save the verification code, obtain the cookie for login, and then directly post data to the login address.
First, use the packet capture tool or Firefox or Google Chrome to analyze the post request and header information on the login page. Take Google as an example.
It can be seen that the url to post is not the accessed page, but http: // 202.115.80.153/default2.aspx,
The TXT username and TextBox2 usernames and passwords in the form data to be submitted are respectively.
Now go directly to the key part of the code !!
Import urllib2import cookielibimport urllibimport reimport sys ''' simulate logon ''' reload (sys) sys. setdefaultencoding ("UTF-8") # prevent Chinese errors CaptchaUrl =" http://202.115.80.153/CheckCode.aspx "PostUrl =" http://202.115.80.153/default2.aspx "# Verification Code address and post address cookie = cookielib. cookieJar () handler = urllib2.HTTPCookieProcessor (cookie) opener = urllib2.build _ opener (handler) # bind cookies to an opener cookie. cookielib automatically manages username = 'username' password = 'password123' # username and password picture = opener. open (CaptchaUrl ). read () # Use openr to access the Verification Code address and obtain cookielocal = open ('e:/image.jpg ', 'wb') local. write (picture) local. close () # Save the verification code to the local SecretCode = raw_input ('Enter the verification code: ') # Open For the saved Verification Code image, enter postData = {'_ viewstate': 'prop/tlA1L + rmL83g =', 'txtusername': username, 'textbox2 ': password, 'txtsecretcode ': secretCode, 'radiobuttonlist1': 'Students ', 'button1': '', 'lblanguage':'', 'hiddrs': '', 'hidd ':'',} # construct the form headers = {'access': 'text/html, application/xhtml + xml, application/xml; q = 0.9, image/webp, */* According to the packet capture information ,*/*; q = 0.8 ', 'Accept-Language': 'zh-CN, zh; q = 0.8 ', 'connect Ion ': 'Keep-alive', 'content-type': 'application/x-www-form-urlencoded', 'user-agent ': 'mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/6666',} # construct headersdata = urllib Based on the packet capture information. urlencode (postData) # generate post data? Key1 = value1 & key2 = value2 form request = urllib2.Request (PostUrl, data, headers) # construct request try: response = opener. open (request) result = response. read (). decode ('gb2312') # because the webpage is encoded by gb2312, You need to decode the print result # print the login page metadata t urllib2.HTTPError, e: print e. code # Use the opener logon page with the previous cookie
After successful logon, you can use this openr to access other pages that require logon.