我需要使用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()
或者
^{pr2}$或者
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()
我想这些方法中的一些使用相同的机制。在
还有其他使用httplib
,httplib2
的例子。我读到urllib2是首选的lib。在
哪种方法是首选方法?它们各自有哪些优点和缺点?在
试试requests-模块,它修复了Python中URL/下载库的疯狂。在
同意Fabian,你应该使用Requests。在
为什么?也许作者自己在这里总结得最好:
Kenneth Reitz's talk "Python For Humans" section on why ^{} is "the worst API" ever 。在
相关问题 更多 >
编程相关推荐