Beautiful Soup在前面关于利用它如何处理Python中文件编码的问题做过一些介绍。最近使用它来解析html文件,为之优雅,简洁的接口设计所折服。它的使用文档可以见这里

从中可以看到Beautiful Soup会读入html文档的内容,然后解析成树的结构,基于树在其中做查找和删除和修改的工作。使用中,有几点需要注意:

1. Beautiful Soup中一些基本元素的概念。

  • tag: html中的标签,可以根据“.”直接访问。如soup.html.head.titile  就可以访问到html中title中的内容。注意这访问到的是完整的title的内容<title>***</title>,而且是一个结构,如果需要赋值给一个串,需要使用str()或者unicode转化之。
  • name, string,attr属性。对于一个标签,如:<a href=”http://www.hongzhixong.com”>my blog</a>,我们可以如下访问到其中的url和熟悉值:
    soup = BeautifuSoup('<a href="http://www.hongzhixong.com">my blog</a>')</li>
    print soup.a   # result: <a href="http://www.hongzhixong.com">my blog</a>
    
    print soup.a.name # result: a
    
    print soup.a.string # result: my blog
    
    print soup.a["href"] # result: http://www.hongzhixong.com
    

    name就是具体tag的名字,string是它的值, 通过字典的形式访问tag的属性值。看起来是不是很方便?

  • contents:是这个树下面的所以子节点,可以通过contents[i]访问到。
  • next, parent,next,previous,nextSibling,previousSibling等属性当作一个树来看,就很容易理解是怎么回事了

2. findAll和find非常强大。使用起来也非常之方便。具体可以见文档。

3 . 比较需要注意的编码问题:在实际的使用过程中,发现Beautiful Soup内部是一unicode的编码来统一处理的,所以像上面的soup.a.string返回的unicode编码的串,你可以使用type(soup.a.string) 会发现这一点。所以,在程序使用find或者split之类操作,且设计到中文时,需要使用unicode编码,如: soup.a.string.find(u”小洪”)。在字符串前面加u。Python中Unicode编程可以见这里

4. 换行问题。Beautiful Soup会将换行作为一个子节点解析,所以建议将html文件的换行和空行做一个简单的过滤后再去解析。

嗯,大致就这么多,当然了,如果涉及到的信息查找不多,而且,效率要求很高,可以简单地使用string的find操作或者正则,因为Beautiful Soup的效率不是很高,需要仔细权衡。

最后,随便提一下Beautiful Soup的主页的标题中有一句话:we called him tortoise because he taught us。我google了一下,是《爱丽丝历险记》中某个章节的对话,Tortoise与taught us音相近。翻译起来是:叫它tortoise是因为它教我们。Tortoise本身是乌龟之意。对这本小说知之甚少,不知道有什么更深的意味。

Tags: .
首页

No Comments Now!

Be the first to comment on this entry.

请您留下评论

名称(必填)
Mail (必填),(will not be published)
网站(recommended)

Fields in bold are required. Email addresses are never published or distributed.

Some HTML code is allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
URLs must be fully qualified (eg: http://www.hongzhixiong.com),and all tags must be properly closed.

Line breaks and paragraphs are automatically converted.

Please keep comments relevant. Off-topic, offensive or inappropriate comments may be edited or removed.