1. 程式人生 > >urllib2 post請求方式

urllib2 post請求方式

ctype length style lines ble -a read imp www

#encoding = utf-8

import urllib2
import urllib

url = ‘http://httpbin.org/post‘
data={"name":"tom","age":22}
data=urllib.urlencode(data)

req=urllib2.Request(url,data)
html=urllib2.urlopen(req)
content = html.readlines()

print u"請求結果內容:"
print content

結果:

D:\>python test.py
請求結果內容:
[‘{\n‘, ‘ "args": {}, \n‘, ‘ "data": "", \n‘, ‘ "files": {}, \n‘, ‘ "form": {\n‘, ‘ "age": "22", \n‘, ‘ "name": "tom"\n‘, ‘ }, \n‘, ‘ "headers": {\n‘, ‘ "Accept-Encoding": "identity", \n‘, ‘ "Connection": "close", \n‘, ‘ "Content-Length": "15", \n‘, ‘ "Content-Type": "application/x-www-form-urlencoded", \n‘, ‘ "Host": "httpbin.org", \n‘, ‘ "User-Agent": "Python-urllib/2.7"\n‘, ‘ }, \n‘, ‘ "json": null, \n‘, ‘ "origin": "119.123.179.3", \n‘, ‘ "url": "http://httpbin.org/post"\n‘, ‘}\n‘]

添加cookie,帶請求頭的方式:

#encoding = utf-8

import urllib2,urllib
import cookielib

url="http://www.renren.com/ajaxLogin"
#定義一個容器,然後定義帶cookie的模板,再定義一個實際的post請求
#創建cj的cookie容器
cj=cookielib.CookieJar()
#用容器創建一個帶有cookie的請求模板
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#將要post發出去的數據進行編碼
data = urllib.urlencode({"email":"18142232233","password":"helloworld"})
request = urllib2.Request("http://www.baidu.com/",data)#post請求模板
request.add_header(‘User-Agent‘,‘Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1)‘)#添加請求頭
r=opener.open(request)#使用帶有cookie模板的請求模板發送post請求
print u"獲取到的cookie為:"
print cj

print u"請求返回的第一行數據"
print r.readline()

結果:

D:\>python test.py
獲取到的cookie為:
<CookieJar[<Cookie BAIDUID=F86188C1F6E5F40C55BE223372AEDCCD:FG=1 for .baidu.com/>, <Cookie BDSVRTM=0 for www.baidu.com/>]>
請求返回的第一行數據
<!DOCTYPE html>

urllib2 post請求方式