python2与python3爬虫中get与post对比的示例分析

这篇文章主要为大家展示了“python2与python3爬虫中get与post对比的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“python2与python3爬虫中get与post对比的示例分析”这篇文章吧。

python2中的urllib2改为python3中的urllib.request

四种方式对比:

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

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

# 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

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'))

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'))

以上是“python2与python3爬虫中get与post对比的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!