python爬虫初探

来源:互联网 发布:python sip协议 编辑:程序博客网 时间:2024/06/05 06:10

由于项目需要,需要抓取某些网站数据,抓取后收集用作大数据分析,展示,但是基于网站,网页的数据抓取,每次数据量不大,所以用python,go(本文用python).但是每个网站的编码格式也不一样,所以需要下载chardet 进行相应的网页编码格式进行解码,编码,避免进行手工判断.以下为抓取网页例子


1.安装chatdet,此处为ubunt 安装,linux安装可以下载chardet-*.gz安装包,解压后放到对应使用python lib目录,否则idea,pycharm无法识别,所以此时确认你的python编译器目录是否正确是重中之重,确保程序引用类库是否是引用的该目录,否则会出现pip install chardet 后,无法在项目中调用chardet的窘相.

a. 下载,gz 

官方地址


b.安装[此为python2.7]

1. 解压*.gz文件放到python 类库目录  /usr/lib/python2.7/dist-packages  

2.使用pip  insall  chardet 



爬虫代码


#-*-coding:utf-8-*-import urllib2import chardet as chardetimport  reclass Demo2:  def readData(self):        url_link  = 'https://www.1688.com/chanpin/-B9E3B6ABC0F3D6A6.html'        #get pages 设置超时时间        #html = urllib2.urlopen(url_link,timeout=30).read()        source_html = urllib2.urlopen('https://www.1688.com/chanpin/-B9E3B6ABC0F3D6A6.html').read()        #print html        mychar = chardet.detect(source_html)        encode = mychar['encoding']        if encode =='utf-8' or encode =='UTF-8':            source_data=source_html        elif encode =='gbk' or encode =='GBK':            #如与程序编码格式utf-8不一致,gbk,则使用utf-8进行解码后再编码            source_data = source_html.decode('gbk','ignore').encode('utf-8')        elif encode =='gb2312' or encode == 'GB2312':            source_data = source_html.decode('gb2312','ignore').encode('utf-8')        #print  source_data        #print  '\n',type(source_data)        #返回抓取的数据        return  source_data  def  matchData(self,sourcedata):       regEx = r'<a click-item="price".*>.*</a>'       #返回pattern对象       rules = re.compile(regEx)       #for i in sourcedata       #根据patter对象对字符串进行匹配       result = rules.findall(source_data,0,len(source_data))       for i in result:           regEx2 = r'</i>.*</span>'           rules2 = re.compile(regEx2)           res = rules2.findall(i,0,len(i))           regEx3 = r'>.*<'           rules2 = re.compile(regEx3)           res3 = rules2.findall(res)           print  res3       return  resultif __name__ == '__main__':     demo = Demo2()     source_data = demo.readData()     result = demo.matchData(sourcedata=source_data)     #print  result

原创粉丝点击