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

yipeiwu_com6年前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爬虫爬取电影天堂资源的文章,重点是如何解析页面和提高爬虫的效率。由于电影天堂上的资源获取权限是所有人都一样的,所以不需要进行登录验证操作,写完那篇文章后又花...

python抓取最新博客内容并生成Rss

osc的rss不是全文输出的,不开心,所以就有了python抓取osc最新博客生成Rss # -*- coding: utf-8 -*- from bs4 import Beau...

Python爬取读者并制作成PDF

学了下beautifulsoup后,做个个网络爬虫,爬取读者杂志并用reportlab制作成pdf.. crawler.py 复制代码 代码如下: #!/usr/bin/env pyth...

python爬虫入门教程--快速理解HTTP协议(一)

python爬虫入门教程--快速理解HTTP协议(一)

前言 爬虫的基本原理是模拟浏览器进行 HTTP 请求,理解 HTTP 协议是写爬虫的必备基础,招聘网站的爬虫岗位也赫然写着熟练掌握HTTP协议规范,写爬虫还不得不先从HTTP协议开始讲...

python爬虫之自制英汉字典

python爬虫之自制英汉字典

最近在微信公众号中看到有人用Python做了一个爬虫,可以将输入的英语单词翻译成中文,或者把中文词语翻译成英语单词。笔者看到了,觉得还蛮有意思的,因此,决定自己也写一个。 首先我们的爬虫...