【python】python2.x 与 python3.x区别对照+缩进错误解决方法
仅仅列出我用到的,不全。
划重点:
1. urllib2 用 urllib.request 代替
2. urllib.urlencode 用 urllib.parse.urlencode 代替
3. cookielib 用 http.cookiejar 代替
4. print " " 用 print(" ") 代替
5. urllib2.URLError 用 urllib.error.URLError 代替
6. urllib2.HTTPError 用 urllib.error.HTTPError 代替
7. except urllib2.URLError, e: 用 except urllib.error.URLError as e: 代替
在python3.4.3自带的IDLE中写代码,经常出现缩进错误,很难查找。
解决方案:拷贝到Notepad++里面,视图中显示空格和制表符,就可以明显看出问题在哪了。
设置了header的网络请求,在Python2.x中的写法
import urllib
import urllib2 url = 'http://www.server.com/login'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'username' : 'kzy', 'password' : '' }
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request)
page = response.read()
在Python3.x中的写法
import urllib.parse
import urllib.request url = 'http://www.baidu.com'
user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36'
values = {'username':'kzy','password':''}
headers = {'User-Agent':user_agent}
data = urllib.parse.urlencode(values).encode(encoding='UTF8') #这里要指明编码方式
request = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(request)
page = response.read()
我在学习静觅的爬虫教程,照着把里面的基础部分的代码都写了一遍。
教程地址:http://cuiqingcai.com/1052.html
里面原本的代码都是2.x的,我全部用3.x学着写了一遍。如下:
import urllib.parse
import urllib.request """
response = urllib.request.urlopen("http://www.baidu.com")
print(response.read())
""" """
#设置了header和data的请求 url = 'http://www.baidu.com'
user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36'
values = {'username':'kzy','password':'123'} headers = {'User-Agent':user_agent} data = urllib.parse.urlencode(values).encode(encoding='UTF8') request = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(request) page = response.read()
""" """
#设置代理 避免因为某个IP的访问次数过多导致的禁止访问
enable_proxy = True
proxy_handler = urllib.request.ProxyHandler({"http":'http://some-proxy.com:8080'}) null_proxy_handler = urllib.request.ProxyHandler({}) if enable_proxy:
opener = urllib.request.build_opener(proxy_handler)
else:
opener = urllib.request.build_opener(null_proxy_handler) urllib.request.install_opener(opener) """ """ #设置Timeout
response = urllib.request.urlopen('http://www.baidu.com', timeout = 10)
""" """
#使用http的 put或delete方法
url = 'http://www.baidu.com'
request = urllib.request.Request(url, data=data)
request.get_method = lambda:'PUT' #or 'DELETE'
response = urllib.request.urlopen(request)
""" """
#使用DebugLog 把收发包的内容在屏幕上打印出来 方便调试
httpHandler = urllib.request.HTTPHandler(debuglevel=1) httpsHandler = urllib.request.HTTPSHandler(debuglevel=1)
opener = urllib.request.build_opener(httpHandler, httpsHandler) urllib.request.install_opener(opener)
response = urllib.request.urlopen('https://its.pku.edu.cn/netportal/netportal_UTF-8.jsp', timeout = 5)
""" """
#URLError异常处理 from urllib.error import URLError, HTTPError
request = urllib.request.Request('http://www.baidu.com')
try:
urllib.request.urlopen(request, timeout = 5)
except HTTPError as e:
print('Error code:', e.code)
except URLError as e: print('Reason:', e.reason)
""" """
#URLError异常处理 属性判断
request = urllib.request.Request('https://its.pku.edu.cn/netportal/netportal_UTF-8.jsp')
try:
urllib.request.urlopen(request, timeout = 5)
except urllib.error.URLError as e:
if hasattr(e, "code"): #hasattr 判断变量是否有某个属性
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
else:
print("OK")
""" """
#获取cookie保存到变量
import http.cookiejar
#声明一个CookieJar对象实例来保存cookie
cookie = http.cookiejar.CookieJar()
#利用HTTPCookieProcessor对象来创建cookie处理器
handler = urllib.request.HTTPCookieProcessor(cookie)
#通过handler来构建opener
opener = urllib.request.build_opener(handler)
#此处的open方法同urlopen
response = opener.open('https://its.pku.edu.cn/netportal/netportal_UTF-8.jsp')
for item in cookie:
print('Name = '+item.name)
print('Value = '+item.value)
""" """ #获取cookie保存到文件 import http.cookiejar #设置保存的文件 filename = 'cookie.txt' #声明一个MozillaCookieJar对象实例来保存cookie,之后写入文件
cookie = http.cookiejar.MozillaCookieJar(filename) #创建cookie处理器 handler = urllib.request.HTTPCookieProcessor(cookie)
#构建opener opener = urllib.request.build_opener(handler) response = opener.open("https://its.pku.edu.cn/netportal/netportal_UTF-8.jsp") #保存到cookie文件 cookie.save(ignore_discard=True,ignore_expires=True)
""" """
#从文件中获取cookie并访问 import http.cookiejar #创建MozillaCookieJar实例对象 cookie = http.cookiejar.MozillaCookieJar() #从文件中读取cookie内容到变量 cookie.load('cookie.txt',ignore_discard=True,ignore_expires=True) #创建请求的request
req = urllib.request.Request('https://its.pku.edu.cn/netportal/netportal_UTF-8.jsp')
#创建opener opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))
response = opener.open(req)
print(response.read())
""" #模拟登陆 登陆不成功
import http.cookiejar filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))
postdata = urllib.parse.urlencode({'stuid':'******','pwd':'******'}).encode(encoding='UTF8') #这里怎么知道名字分别是stuid和pwd呢???
loginUrl = 'http://xxxxxx.com'
result = opener.open(loginUrl, postdata)
cookie.save(ignore_discard=True, ignore_expires=True)
gradeUrl='http://xxxxxx.com'
result = opener.open(gradeUrl)
print(result.read())
【python】python2.x 与 python3.x区别对照+缩进错误解决方法的更多相关文章
- Python 排错UnicodeEncodeError 'ascii' codec can't encode character 错误解决方法
Python UnicodeEncodeError 'ascii' codec can't encode character 错误解决方法 by:授客 QQ:1033553122 错误描述: py ...
- Python更新pip出现错误解决方法
Python更新pip出现错误解决方法 更新pip python -m pip install --upgrade pip 查看时报错 解决方法 在命令栏(即win+r)输入:easy_install ...
- Python决策树可视化:GraphViz's executables not found的解决方法
参考文献: [1]Python决策树可视化:GraphViz's executables not found的解决方法
- python使用pip安装第三方模块遇到的问题及解决方法
python使用pip安装第三方模块遇到的问题及解决方法 关注公众号"轻松学编程"了解更多. 使用国内源: 清华:https://pypi.tuna.tsinghua.edu.cn ...
- python之路-python2.x与python3.x区别
Python崇尚优美.清晰.简单,是一个优秀并广泛使用的语言. Python2.x 与 Python3.x的区别: python2.x:源码混乱,重复代码较多,冗余. python3.x:源码规范,崇 ...
- Python语言基础-语法特点、保留字与标识符、变量、基本数据类型、运算符、基本输入输出、Python2.X与Python3.X区别
Python语言基础 1.Python语法特点 注释: 单行注释:# #注释单行注释分为两种情况,例:第一种#用于计算bim数值bim=weight/(height*height)第二种:bim=we ...
- python2.X与Python3.X区别
__future__模块 [回到目录] Python 3.x引入了一些与Python 2不兼容的关键字和特性,在Python 2中,可以通过内置的__future__模块导入这些新内容.如果你希望在P ...
- windows python3.7安装numpy问题的解决方法
我的是win7的系统,去python官网下载python3.7安装 CMD #打开命令窗口 pip install numpy #在cmd中输入 提示 需要c++14.0, 解决办法: 1, 进入h ...
- Python学习:ModuleNotFoundError: No module named 'pygal.i18n' 的解决方法
最近在学<Python编程:从入门到实践>,16.2小结中 from pygal.i18n import COUNTRIES 获取两个字母的国别码,我用的pygal的版本是2.4.0(终端 ...
随机推荐
- SQLAlchemy 学习笔记(二):ORM
照例先看层次图 一.声明映射关系 使用 ORM 时,我们首先需要定义要操作的表(通过 Table),然后再定义该表对应的 Python class,并声明两者之间的映射关系(通过 Mapper). 方 ...
- NO4——并查集
int find(int x) { int r = x; while(father[r]!=r) r = father[r]; return r; } /* int find(int x) { if( ...
- Introduction to TCP/IP
目录 First Week DHCP 子网掩码 ip路由表 Second Week ipv4 ipv6 TCP和UDP Third Week NAT RPC FTP E-mail Fouth Week ...
- hbase1.2.6完全分布式安装
环境,参考之前的两篇博文: jdk1.7 hadoop2.6.0 完全分布式 一个master,slave1,slave2,slave3 zookeeper3.4.6 完全分布式 安装与配置:(以下步 ...
- div clear清除浮动产生的影响 被受影响的div加上清除浮动后 不会填充前一个div浮动后空出的位置
- SRM709 div1 Xscoregame(状压dp)
题目大意: 给定一个序列a,包含n个数(n<=15),每个数的大小小于等于50 初始时x = 0,让你每次选a中的一个数y,使得x = x + x^y 问如何安排选择的次序,使得最终结果最大. ...
- 学习python类
类:Python 类提供了面向对象编程的所有基本特征: 允许多继承的类继承机制, 派生类可以重写它父类的任何方法, 一个方法可以调用父类中重名的方法. 对象可以包含任意数量和类型的数据成员. 作为模块 ...
- Ubuntu 编译Webkit --gtk
转载自:http://www.linuxidc.com/Linux/2011-10/44809.htm webkit是一个浏览器内核,google的chrome就是基于它的,下面介绍一下如何在Ubun ...
- notepad++中快速插入当前时间方法
转载自:http://blog.csdn.net/donghustone/article/details/7436483 在notepad++中快速插入当前时间方法: 插件是notepad++的一大优 ...
- 如何解决DuplicateFileException: Duplicate files copied in APK问题
问题:有重复的文件存在APK里 解决方案:在Module里的build.gradle中设置忽略此重复文件即可.