Python mimics the way POST submits HTTP data and USES Cookie values

  • 2020-04-02 14:19:07
  • OfStack

This article illustrates how to simulate POST HTTP data and submit data with Cookie in Python. The specific implementation method is as follows:

Methods a

If you don't use cookies, sending an HTTP POST is very simple:

import urllib2, urllib
data = {'name' : 'www', 'password' : '123456'}
f = urllib2.urlopen(
        url     = '//www.jb51.net/',
        data    = urllib.urlencode(data)
  )
print f.read()

When using cookies, the code gets a little more complicated:
import urllib2
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)
f = opener.open('http://www.xxxx.net/?act=login&name=user01')
data = '<root>Hello</root>'
request = urllib2.Request(
        url     = 'http://www.xxxx.net/?act=send',
        headers = {'Content-Type' : 'text/xml'},
        data    = data)
opener.open(request)

The first open() is a login. The Cookie returned by the server is automatically saved in cookies and used for subsequent requests.

The second open() USES the POST method to send content-type =text/ XML data to the server. If you do not create a Request but use the urlopen() method directly, Python forces the content-type to be changed to application/x-www-form-urlencoded.

Method 2

Urllib2 library, with Cookie request URL page

Case 1:

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

Example 2:
import urllib2
import urllib
from cookielib import CookieJar
 
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()

I hope this article has helped you with your Python programming.


Related articles: