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抓取了7000 多本电子书案例详解

我用Python抓取了7000 多本电子书案例详解

安装 安装很简单,只要执行: pip install requests-html 就可以了。 分析页面结构 通过浏览器审查元素可以发现这个电子书网站是用 WordPress 搭建的...

python抓取网页中的图片示例

复制代码 代码如下:#coding:utf8import reimport urllibdef getHTML(url):    page = urllib...

Python 爬虫实现增加播客访问量的方法实现

一、序言: 世界 1024 程序猿节日不加班,闲着没事儿。。。随手写了个播客访问量爬虫玩玩,访问量过万不是事儿!!!每个步骤注释都很清晰,代码仅供学习参考! ---- Nick.Pen...

python 爬虫一键爬取 淘宝天猫宝贝页面主图颜色图和详情图的教程

实例如下所示: import requests import re,sys,os import json import threading import pprint class s...

python爬虫实战之最简单的网页爬虫教程

python爬虫实战之最简单的网页爬虫教程

前言 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。最近对python爬虫有了强烈地兴趣...