• Python学习 - 使用BeautifulSoup来解析网页一:基础入门


    写技术博客主要就是总结和交流的,如果文章用错,请指正啊!

    以前一直在使用SGMLParser,这个太费时间和精力了,现在为了毕业设计,改用BeautifulSoup来实现HTML页面的解析工作的。

    一、字符的编码和解码

      和网页打交道,首先解决的就是web页面的编码方式,不幸的是不同网站的页面编码方式基本不相同,有的是gb2312,有的是utf-8,有的是gbk,下面是我查看我以后需要的网站源码后得出的web页面的编码方式:

    di = { 'gb2312':['http://www.sina.com.cn','http://www.people.com.cn/','http://www.people.com.cn/'
                     ,'http://www.163.com/','http://www.qq.com/'],
          'gbk':['http://www.sohu.com'],
          'utf-8':['http://www.huanqiu.com/','http://www.xinhuanet.com/']
          }
    

      这个python字典,我会一直手动更新的。为什么需要手动更新呢?因为我不会动态的检测web页面的编码方式,虽然说HTTP的Header中有content的编码方式,即Content-Type这一项,但是上面的网站基本上都没有在Content-Type中表明编码方式,翻墙看了一下谷歌,youtube和facebook,在Content-Type里面都表明了编码方式,一般都为utf-8。

      知道了编码方式,就要解码了,因为BeautifulSoup先将html页面全部转码为unicode的,所以在将html页面传入BeautifulSoup中的时候,先解码,如果html的字符编码为gb2312:

    response = urllib2.urlopen(url).read().decode('gb2312','ignore')
    bs = BeautifulSoup(response)

      如果你想将unicode字符编码为特定的编码方式:  

    response = urllib2.urlopen(url).read().decode('gb2312','ignore').encode('utf-8')
    

      因为业务场景不一样,我只需要抓取部分网站的页面,所以我手动查看了上面几个网站的编码方式。当然有其它的方法了,见我在stackoverflow上的提问:http://stackoverflow.com/questions/28184863/how-to-decode-and-encode-web-page-with-python 。

    二、解压

    很多网站为了减少流量,将页面压缩。常见的压缩方式为gzip,随便百度一下就可以收到解压gzip文件的代码:

    def unzip(data):
            import gzip
            import StringIO
            data = StringIO.StringIO(data)
            gz = gzip.GzipFile(fileobj=data)
            data = gz.read()
            gz.close()
            return data
    

    其它的压缩方式暂不讨论。

    三、一个很丑陋的demo

    # -*- coding: utf-8 -*-
    '''
    Created on 2015年1月28日
    
    @author: zhang
    '''
    from bs4 import BeautifulSoup
    
    result = {}
    key_word = u'李克强'
    
    def unzip(data):
            import gzip
            import StringIO
            data = StringIO.StringIO(data)
            gz = gzip.GzipFile(fileobj=data)
            data = gz.read()
            gz.close()
            return data
    
    def init_bs(url,encoding):
        import urllib2
        html_doc = ''
        respone = urllib2.urlopen(url)
        header = respone.info()
        
        if 'Content-Encoding' in header:
            if header['Content-Encoding'] == 'gzip':
     
                html_doc = unzip(respone.read()).decode(encoding,'ignore')
            else:
                pass
        else:
            html_doc = respone.read().decode(encoding,'ignore')
        return(BeautifulSoup(html_doc))
    
    def get_target(soup):
        for link in soup.find_all('a'):
            text = link.get_text()
            if text.find(key_word) != -1:
                result[link.get('href')] = text
    
    
    
    di = { 'gb2312':['http://www.sina.com.cn','http://www.people.com.cn/','http://www.people.com.cn/'
                     ,'http://www.163.com/','http://www.qq.com/'],
          'gbk':['http://www.sohu.com'],
          'utf-8':['http://www.huanqiu.com/','http://www.xinhuanet.com/']
          }
    
    for k,v in di.iteritems():
        for url in v:
            
            soup = init_bs(url,'gb2312')
            get_target(soup)
            
    
    for k,v in result.iteritems():
        print k,v
        
    

      

  • 相关阅读:
    asp.net实现bt和pt协议—torrent
    asp.net实现bt和pt协议bencode
    asp.net实现bt和pt—tracker response
    asp.net实现bt和pt——邪恶篇:PtCheater
    自我介绍
    [转载]直接保存Matlab图像到PPT文件
    中断过程与主程序调用子程序过程的比较
    [转载]转贴:大学电子类专业学生忠告
    2010年10月26日
    [转载]win7命令大全
  • 原文地址:https://www.cnblogs.com/mr-zys/p/4255558.html
Copyright © 2020-2023  润新知