发出HTTP [S]请求的首选方法

时间:2012-10-23 08:09:49

标签: python http httprequest urllib2 urllib

我需要使用POST,GET和其他方法发出HTTP和HTTPS请求,并指定标头和超时。

在互联网上有很多例子,它们都是不同的:

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()

    fetcher = urllib2.build_opener()
    fetcher.addheaders.append(('Cookie', 'aaaa=%s' % aaaa))
    res = fetcher.open(settings.ABC_URL)

req = urllib2.Request(url=url)
req.add_header('X-Real-IP', request.META['REMOTE_ADDR'])
req.add_header('Cookie', request.META['HTTP_COOKIE'])
req.add_header('User-Agent', request.META['HTTP_USER_AGENT'])
resp = urllib2.urlopen(req).read()

handler = urllib.urlopen('http://...')
response = handler.read()

我想这些方法中有一些使用相同的机制。

还有其他使用httplibhttplib2的示例。我读过urllib2是首选的lib。

哪一个是首选方法?各自有哪些优点和缺点?

2 个答案:

答案 0 :(得分:6)

试用requests - 模块修复Python中的URL /下载库疯狂。

答案 1 :(得分:2)

同意Fabian,你应该使用Requests

为什么呢?也许作者本人在这里最好地总结了它:

Kenneth Reitz's talk "Python For Humans" -- section on why urllib2 is "the worst API" ever