python2.7之【urllib、urllib2】和【requests】实现HTTP请求

环境:python2.7+sublime3

1.【urllib、urllib2】实现http请求:

#-*- coding:utf-8 -*-
import urllib2
import urllib


url_ip = 'http://httpbin.org/ip'
url_get = 'http://httpbin.org/get'


def use_simple_urllib2(url_ip):
	response = urllib2.urlopen(url_ip)
	print ('>>>>>>Response Headers:')
	print (response.info())
	print ('>>>Response Body:')
	print (''.join([line for line in response.readlines()]))

def use_params_urllib2(url_get):
	#构建请求参数
	params = urllib.urlencode({'param1':'hello', 'param2': 'world'})
	print ('Request Params:')
	print (params)
	#发送请求
	response = urllib2.urlopen('?'.join([url_get, '%s'])%params)
	#处理响应
	print ('>>>>>>Response Headers:')
	print (response.info())
	print '>>>Status Code:'
	print response.getcode()
	print ('>>>Response Body:')
	print (''.join([line for line in response.readlines()]))

if __name__ == '__main__':
	print ('>>>Use Simple urllib2:')
	use_simple_urllib2(url_ip)
	print 

	print '>>>Use params urllib2:'
	use_params_urllib2(url_get)


2.【requests】实现HTTP请求:

#-*- coding:utf-8 -*-
import requests

url_ip = 'http://httpbin.org/ip'
url_get = 'http://httpbin.org/get'

def use_simple_requests(url_ip):
	response = requests.get(url_ip)
	print ('>>>>>>Response Headers:')
	print (response.headers)
	print ('>>>Response Body:')
	print response.text

def use_params_requests(url_get):
	#构建请求参数
	params = {'param1':'hello', 'param2': 'world'}
	print ('Request Params:')
	print (params)
	#发送请求
	response = requests.get(url_get, params=params)
	#处理响应
	print ('>>>>>>Response Headers:')
	print (response.headers)
	print '>>>Status Code:'
	print response.status_code
	print response.reason
	print ('>>>Response Body:')
	print response.json()

if __name__ == '__main__':
	print ('>>>Use Simple requests:')
	use_simple_requests(url_ip)
	print 

	print '>>>Use params requests:'
	use_params_requests(url_get)


你可能感兴趣的:(python实例)