Python simulated login implementation code and python simulated code
The following is a small example of simulated website login using Python.
Principle
Use Cookie technology to bypass website login verification. To use the cookielib library. Process:
- Create a Cookie-saving container. Optional values: CookieJar, FileCookieJar, MozillaCookieJar, and LWPCookieJar. The relationships between these two containers are CookieJar -- derived --> FileCookieJar -- derived --> extends illacookiejar and LWPCookieJar.
- Create a Cookie processing processor handler. Use urllib2.HTTPCookieProcessor (cookie ).
- Create an opener for enabling the website. You can. This opener method is more common than urllib2.urlopen. Opener = urllib2.build _ opener (handler ).
- Then we can normally use opener to access the network.
Small Cases
The function is to simulate logon to the educational administration website of Dalian University of Technology. The Code is as follows:
# Coding: UTF-8import urllib, urllib2, cookielibfilename = r 'f: \ pachong \ gaoqing \ dlutcookie.txt '# show cookie and save to localcookie = cookielib. export illacookiejar () handler = urllib2.HTTPCookieProcessor (cookie) opener = urllib2.build _ opener (handler) # Remember to use the urllib module to encodepostdata = urllib for parameters. urlencode ({# Haha, this palace will not give you my account token (token ^ token) Comment 'zshanghai': 'xxxxxxxx', 'mm': 'xxxxxx '}) # login to the educational administration system urlurl = 'HTTP: // zhj1_dlut.edu.cn/lo GinAction. do '# Start simulated login and save the cookie to the variable response = opener. open (url, postdata) cookie. save (filename, ignore_discard = True, ignore_expires = True) # print the obtained cookie information for item in cookie: item. name + '=' + item. value # use cookies to access another website and log on to the URLcourse_url = 'HTTP: // zhj1_dlut.edu.cn/xkaction.do? ActionType = 6 'course _ header = {'user-agent': 'mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) chrome/46.0.2486.0 Safari/537.36 Edge/13.10586 ', 'Referer': 'http: // zhj?dlut.edu.cn/menu/s_main.jsp'=result = opener. open (course_url) print result. read ()
Running result
Summary
In fact, for simulated login, the First Login is to obtain the cookie data. Then we can use the opener we created to complete the next key further operations. All we need to understand is the process of using the cookie.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.