This article mainly uses python to simulate website logon. Construct post data by yourself to implement the login process using Python.
When you want to simulate a website login, you must first understand the details of the website login process (what kind of data is sent, who is sent, etc ...). I use HTTPfox to capture http packets to analyze the login process of the website. At the same time, we also need to analyze the data structure and header of the captured post package, and construct our own post data and header Based on the submitted data structure and heander.
After the analysis, we need to construct our own HTTP packet and send it to the specified url. We use APIs provided by several modules such as urllib2 to send and receive request requests.
Most websites need to carry cookies when logging on, so we must also set cookie processors to ensure cookies.
The code and explanation are as follows:
#! /Usr/bin/python
Import HTMLParser
Import urlparse
Import urllib
Import urllib2
Import cookielib
Import string
Import re
# Logon Homepage
Hosturl = '*******' // enter it by yourself
# Post data receiving and processing page (we want to send the constructed Post data to this page)
Posturl = '*******' // analyzes the data packet and processes the url of the post request.
# Set a cookie processor that downloads cookies from the server to the local machine and carries the local cookies when sending requests
Cj = cookielib. LWPCookieJar ()
Cookie_support = urllib2.HTTPCookieProcessor (cj)
Opener = urllib2.build _ opener (cookie_support, urllib2.HTTPHandler)
Urllib2.install _ opener (opener)
# Open the logon homepage (the purpose is to download the cookie from the page, so that we will have the cookie when sending the post data, otherwise it will not be sent successfully)
H = urllib2.urlopen (hosturl)
# Construct the header. Generally, the header must contain at least two items. These two items are analyzed from the captured bag.
Headers = {'user-agent': 'mozilla/5.0 (Windows NT 6.1; WOW64; rv: 14.0) Gecko/20100101 Firefox/14.0.1 ',
'Referer ':'******'}
# Construct Post data, which is also obtained from the analysis of large packets.
PostData = {'op': 'dmlogin ',
'F': 'st ',
'User': '******', // your Username
'Pass': '*******', // your password. The password may be transmitted in plaintext or ciphertext. If the password is ciphertext, the corresponding encryption algorithm must be called for encryption.
'Rmbr ': 'true', // special data, different websites may be different
'Tmp ': '0. 7306424454308195' // special data, which may be different for different websites
}
# Post data encoding required
PostData = urllib. urlencode (postData)
# Use the request method provided by urllib2 to send the constructed data to the specified Url and complete the login process
Request = urllib2.Request (posturl, postData, headers)
Print request
Response = urllib2.urlopen (request)
Text = response. read ()
Print text
Author: Zhang Hui