python2与python3爬虫中get与post对比解析

yipeiwu_com5年前Python爬虫

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python爬取豆瓣视频信息代码实例

Python爬取豆瓣视频信息代码实例

这篇文章主要介绍了Python爬取豆瓣视频信息代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 这里是爬取豆瓣视频信息,用pyq...

python爬虫入门教程--利用requests构建知乎API(三)

python爬虫入门教程--利用requests构建知乎API(三)

前言 在爬虫系列文章 优雅的HTTP库requests 中介绍了 requests 的使用方式,这一次我们用 requests 构建一个知乎 API,功能包括:私信发送、文章点赞、用户关...

Python爬虫代理IP池实现方法

Python爬虫代理IP池实现方法

在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代理IP,从而保证爬虫快速稳定的运行,当然在公司做的东...

详解Selenium+PhantomJS+python简单实现爬虫的功能

Selenium 一、简介 selenium是一个用于Web应用自动化程序测试的工具,测试直接运行在浏览器中,就像真正的用户在操作一样 selenium2支持通过驱动真实浏览器(Fi...

Python爬虫信息输入及页面的切换方法

实现网页的键盘输入操作 from selenium.webdriver.common.keys import Keys 动态网页有时需要将鼠标悬停在某个元素上,相应的列表选项才能显...