Python2与Python3中Get与Post请求实现对比

晚来风
晚来风
发布时间:2026-10-13 | 2人浏览过
原创

本文详细对比了Python2与Python3在进行网络爬虫开发时,使用urllib模块发起Get和Post请求的代码差异。重点解析了从urllib2到urllib.request的模块迁移,以及数据编码、请求构造和响应处理的具体实现方式,帮助开发者快速掌握版本升级后的代码适配方法。

Python2与Python3模块迁移概述

在Python2中,发起网络请求主要依赖urllib2模块;而在Python3中,该功能已整合至urllib.request模块中。

Get与Post请求实现对比

接下来,我们将通过四种具体场景进行对比分析:

Python2 Get请求实现

首先来看Python2环境下Get请求的实现方式。


# coding=utf-8
import urllib
import urllib2
word = urllib.urlencode({"wd":"百度"})
url = 'http://www.baidu.com/s' + '?' + word
request = urllib2.Request(url)
print urllib2.urlopen(request).read().decode('utf-8')

Python3 Get请求实现

在Python3中,Get请求的实现逻辑有所调整,主要涉及urllib.request和urllib.parse模块的配合使用。


import urllib.request
import urllib.parse
data = urllib.parse.urlencode({'wd':'百度'})
url = 'http://wwww.baidu.com/s?' + data
# url = 'http://www.baidu.com/s?wd=' + urllib.parse.quote('百度')
response = urllib.request.urlopen(url)
print (response.read().decode('utf-8'))

Python2 Post请求实现

接着分析Python2环境下的Post请求实现。


# coding=utf-8
import urllib
import urllib2
formdata = {
  'name':'百度'
}
data = urllib.urlencode(formdata)
request = urllib2.Request(url = "http://httpbin.org/post", data=data)
response = urllib2.urlopen(request)
print response.read()

Python3 Post请求实现

在Python3中,Post请求需要注意数据编码为字节流,并通过urllib.request.urlopen发送。


import urllib.parse
import urllib.request

data = bytes(urllib.parse.urlencode({'name':'百度'}),encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read().decode('utf-8'))

或者,也可以直接构造Request对象来发送Post请求。


import urllib.parse
import urllib.request
request = urllib.request.Request('http://httpbin.org/post',data=bytes(urllib.parse.urlencode({'name':'百度'}),encoding='utf8))'))
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))

以上内容即为本文的全部讲解,希望能为您的学习提供有益参考,也欢迎继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表