仅仅列出我用到的,不全。

划重点:

  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区别对照+缩进错误解决方法的更多相关文章

  1. Python 排错UnicodeEncodeError 'ascii' codec can't encode character 错误解决方法

    Python UnicodeEncodeError 'ascii' codec can't encode character 错误解决方法   by:授客 QQ:1033553122 错误描述: py ...

  2. Python更新pip出现错误解决方法

    Python更新pip出现错误解决方法 更新pip python -m pip install --upgrade pip 查看时报错 解决方法 在命令栏(即win+r)输入:easy_install ...

  3. Python决策树可视化:GraphViz's executables not found的解决方法

    参考文献: [1]Python决策树可视化:GraphViz's executables not found的解决方法

  4. python使用pip安装第三方模块遇到的问题及解决方法

    python使用pip安装第三方模块遇到的问题及解决方法 关注公众号"轻松学编程"了解更多. 使用国内源: 清华:https://pypi.tuna.tsinghua.edu.cn ...

  5. python之路-python2.x与python3.x区别

    Python崇尚优美.清晰.简单,是一个优秀并广泛使用的语言. Python2.x 与 Python3.x的区别: python2.x:源码混乱,重复代码较多,冗余. python3.x:源码规范,崇 ...

  6. Python语言基础-语法特点、保留字与标识符、变量、基本数据类型、运算符、基本输入输出、Python2.X与Python3.X区别

    Python语言基础 1.Python语法特点 注释: 单行注释:# #注释单行注释分为两种情况,例:第一种#用于计算bim数值bim=weight/(height*height)第二种:bim=we ...

  7. python2.X与Python3.X区别

    __future__模块 [回到目录] Python 3.x引入了一些与Python 2不兼容的关键字和特性,在Python 2中,可以通过内置的__future__模块导入这些新内容.如果你希望在P ...

  8. windows python3.7安装numpy问题的解决方法

    我的是win7的系统,去python官网下载python3.7安装 CMD  #打开命令窗口 pip install numpy #在cmd中输入 提示 需要c++14.0, 解决办法: 1, 进入h ...

  9. Python学习:ModuleNotFoundError: No module named 'pygal.i18n' 的解决方法

    最近在学<Python编程:从入门到实践>,16.2小结中 from pygal.i18n import COUNTRIES 获取两个字母的国别码,我用的pygal的版本是2.4.0(终端 ...

随机推荐

  1. Linux 简单socket实现TCP通信

    服务器端代码 #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <stri ...

  2. 学习MVC中出现的一个BUG

    BUG描述:No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.S ...

  3. java线程(5)——线程池(上)

    引入: 在之前的例子中,我们需要使用线程时就直接去创建一个线程,这样既不浪费资源又十分方便.但如果我们需要创建多个并发的线程,而且短时间执行就结束了,如果还用之前的方式,就会大大降低效率和性能了. 因 ...

  4. doget,doPost在底层走的是service

    doget,doPost在底层走的是service 因为在源码上 先执行service方法 然后再调用doget,doPost方法

  5. [HAOI2010]计数

    题面在这里 description 你有一组非零数字(不一定唯一),你可以在其中插入任意个0,这样就可以产生无限个数. 比如说给定{1,2},那么可以生成数字12,21,102,120,201,210 ...

  6. 机器学习模型-支持向量机(SVM)

    二.代码实现 import numpy as np from sklearn import datasets from sklearn.model_selection import train_tes ...

  7. NOIP2010 引水入城 贪心+DFS

    我们先把简单的不能搞死,具题意可证:每个蓄水长的管辖区域一定是连续的.证明:既然我们已经能了那么我们就可以说如果这个区间不是连续的那我们取出这个区间中间阻隔开的那一段,那么对于这一整个区间来说水源不可 ...

  8. MySQL:BlackHole

    MySQL:BlackHole 顾名思义BlackHole就是黑洞,只有写入没有输出.现在就来实验一下吧 首先查看一下MySQL支持的存储引擎 mysql> show engines;+---- ...

  9. CSS中z-index全解析

    一.z-index解释 z-index属性决定了一个HTML元素的层叠级别,元素层叠级别是相对于元素在Z轴上(与X轴Y轴相对照)的位置而言.一个更高的z-index值意味着这个元素在叠层顺序中会更靠近 ...

  10. windows mysql 安装及启动

    0.下载: