Python3 send a POST request to automatically remember cookies

Source: Internet
Author: User
Tags urlencode

When you do a POST request to log in, you need to remember the cookie, or you cannot access the post-login page.

Here is the code for the login:

#coding: Utf-8
Import Urllib
Import Http.cookiejar

url = "Http://c.highpin.cn/Users/CLogin"
PostData =urllib.parse.urlencode ({
"Logon_password": "SunMin",
"Logon_postcode": "FGHC",
"Logon_rememberme": "false",
"Logon_useremail": "[email protected]"
}). Encode (' Utf-8 ')
Header = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-encoding": "Utf-8",
"Accept-language": "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
"Connection": "Keep-alive",
"Host": "c.highpin.cn",
"Referer": "http://c.highpin.cn/",
"User-agent": "mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) gecko/20100101 firefox/32.0 "
}
req = Urllib.request.Request (Url,postdata,header)
# #print (Urllib.request.urlopen (req). Read (). Decode (' Utf-8 '))

#自动记住cookie
CJ = Http.cookiejar.CookieJar ()
Opener = Urllib.request.build_opener (Urllib.request.HTTPCookieProcessor (CJ))
R = Opener.open (req)
Print (R.read (). Decode (' Utf-8 '))

Used to be python2.7, but Python3 started a lot of packages and the location of the former is not the same, the use of the instructions here:

URLLIB2 merged into Urllib, Urlopen uses the package location for Urllib.request.urlopen,urlencode using the package position as Urllib.parse.urlencode

Cookielib Change to Http.cookiejar

Note: Printing with a cookie must be made with Opener.open (req). Read (). Decode (' Utf-8 ') to send a request before a cookie is brought with the Urllib.request.urlopen () It's not with cookies.

Python3 and Python2 changes, you can refer to the article: http://blog.csdn.net/samxx8/article/details/21535901

Python3 send a POST request to automatically remember cookies

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.