Python imitates the POST method to submit HTTP data and use the Cookie value.
This article describes how to simulate post http data and submit data with cookies in Python. The specific implementation method is as follows:
Method 1
If you do not use cookies, it is very easy to send http post:
Copy codeThe Code is as follows: import urllib2, urllib
Data = {'name': 'www ', 'Password': '000000 '}
F = urllib2.urlopen (
Url = 'HTTP: // www.bkjia.com /',
Data = urllib. urlencode (data)
)
Print f. read ()
When using cookies, the Code becomes a bit complex:
Copy codeThe Code is as follows: 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 used to log on. The Cookie returned by the server is automatically stored in cookies and used in subsequent requests.
The second open () method sent Content-Type = text/xml data to the server using the POST method. if you do not create a Request, but directly use the urlopen () method, Python forcibly changes Content-Type to application/x-www-form-urlencoded.
Method 2
Use the urllib2 library to request URL pages with cookies
Example 1:
Copy codeThe Code is as follows: import urllib2
Opener = urllib2.build _ opener ()
Opener. addheaders. append ('cookiename = cookievalue '))
F = opener. open ("http://example.com /")
Example 2:
Copy codeThe Code is as follows: 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 will help you with Python programming.