标签:user dsv win build header type post请求 mail uil
#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>
”
标签:user dsv win build header type post请求 mail uil
原文地址:https://www.cnblogs.com/xiaxiaoxu/p/10274704.html