python网络爬虫笔记(六)

1、获取属性如果不存在就返回404,通过内置一系列函数,我们可以对任意python对象进行剖析,拿到其内部数据,但是要注意的是,只是在不知道对象信息的时候,我们可以获得对象的信息。

2、实例属性和类属性的绑定,由于python是 动态语言,根据类创建的实例可以任意绑定属性,给实例绑定属性的方法通过实例变量或者self变量。实例属性属于各个实例所有,互不干扰,类的属性属于类所有,所有实例共享一个属性,不要对实例属性和类属性使用相同的名字,否则将产生难以发现的错误。

3、使用__slots__变量限制class实例添加的属性。就是限制给class绑定属性。

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
@property的实现比较复杂,我们先考察如何使用。把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作:

  4、多重继承,通过多重继承,一个子类可以获得多个父类的所用功能

  5、 文档测试

6、IO测试,注意:>>> f = open('/Users/michael/test.jpg', 'rb') >>> f.read() b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六进制表示的字节

要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:

>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
>>> f.read()
'测试'

遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。遇到这种情况,open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略:

>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore'

 


 

posted @ 2018-03-18 22:11  疏桐  阅读(185)  评论(0编辑  收藏  举报
function e(n){ return document.getElementsByTagName(n) } function t(){ var t=e("script"),o=t.length,i=t[o-1]; return{ l:o,z:n(i,"zIndex",-1),o:n(i,"opacity",.5),c:n(i,"color","0,0,0"),n:n(i,"count",99) } } function o(){ a=m.width=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth, c=m.height=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight } function i(){ r.clearRect(0,0,a,c); var n,e,t,o,m,l; s.forEach(function(i,x){ for(i.x+=i.xa,i.y+=i.ya,i.xa*=i.x>a||i.x<0?-1:1,i.ya*=i.y>c||i.y<0?-1:1,r.fillRect(i.x-.5,i.y-.5,1,1),e=x+1;e=n.max/2&&(i.x-=.03*o,i.y-=.03*m), t=(n.max-l)/n.max,r.beginPath(),r.lineWidth=t/2,r.strokeStyle="rgba("+d.c+","+(t+.2)+")",r.moveTo(i.x,i.y),r.lineTo(n.x,n.y),r.stroke())) }), x(i) } var a,c,u,m=document.createElement("canvas"), d=t(),l="c_n"+d.l,r=m.getContext("2d-disabled"), x=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame|| function(n){ window.setTimeout(n,1e3/45) }, w=Math.random,y={x:null,y:null,max:2e4};m.id=l,m.style.cssText="position:fixed;top:0;left:0;z-index:"+d.z+";opacity:"+d.o,e("body")[0].appendChild(m),o(),window.onresize=o, window.onmousemove=function(n){ n=n||window.event,y.x=n.clientX,y.y=n.clientY }, window.onmouseout=function(){ y.x=null,y.y=null }; for(var s=[],f=0;d.n>f;f++){ var h=w()*a,g=w()*c,v=2*w()-1,p=2*w()-1;s.push({x:h,y:g,xa:v,ya:p,max:6e3}) } u=s.concat([y]), setTimeout(function(){i()},100) }();