Chinaunix首页 | 论坛 | 博客
  • 博客访问: 534646
  • 博文数量: 71
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 159
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-13 12:37
个人简介

aaaaaaaaa

文章分类

全部博文(71)

文章存档

2013年(71)

我的朋友

分类: Python/Ruby

2013-07-24 12:45:43

下面的内容节选自http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html

Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree)。 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作。它可以大大节省你的编程时间。 对于Ruby,使用Rubyful Soup。

1. 解析html

下面的代码是Beautiful Soup基本功能的示范。你可以复制粘贴到你的python文件中,自己运行看看。
  1. from BeautifulSoup import BeautifulSoup
  2. import re

  3. doc = ['Page title',
  4.        '

    This is paragraph one.',

  5.        '

    This is paragraph two.',

  6.        '']
  7. soup = BeautifulSoup(''.join(doc))

  8. print soup.prettify()
  9. # <html>
  10. # <head>
  11. # <title>
  12. # Page title
  13. # </title>
  14. # </head>
  15. # <body>
  16. # <p id="firstpara" align="center">
  17. # This is paragraph
  18. # <b>
  19. # one
  20. # </b>
  21. # .
  22. # </p>
  23. # <p id="secondpara" align="blah">
  24. # This is paragraph
  25. # <b>
  26. # two
  27. # </b>
  28. # .
  29. # </p>
  30. # </body>
  31. # </html>
navigate soup的一些方法:
  1. soup.contents[0].name
  2. # u'html'

  3. soup.contents[0].contents[0].name
  4. # u'head'

  5. head = soup.contents[0].contents[0]
  6. head.parent.name
  7. # u'html'

  8. head.next
  9. # <title>Page title</title>

  10. head.nextSibling.name
  11. # u'body'

  12. head.nextSibling.contents[0]
  13. # <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>

  14. head.nextSibling.contents[0].nextSibling
  15. # <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>
findAll方法中的text 是一个用于搜索NavigableString对象的参数。 它的值可以是字符串,一个正则表达式, 一个list或dictionary,True或None,  一个以NavigableString为参数的可调用对象,如果你使用text,任何指定给name 以及keyword参数的值都会被忽略。
  1. soup.findAll(text="one")
  2. # [u'one']
  3. soup.findAll(text=u'one')
  4. # [u'one']

  5. soup.findAll(text=["one", "two"])
  6. # [u'one', u'two']

  7. soup.findAll(text=re.compile("paragraph"))
  8. # [u'This is paragraph ', u'This is paragraph ']

  9. soup.findAll(text=True)
  10. # [u'Page title', u'This is paragraph ', u'one', u'.', u'This is paragraph ',
  11. # u'two', u'.']

  12. soup.findAll(text=lambda(x): len(x) < 12)
  13. # [u'Page title', u'one', u'.', u'two', u'.']
下面的两个函数分别是获得html某元素子元素的所有文本内容,以及获得元素后续所有兄弟元素的文本内容
  1. def get_all_text_from_soup(item):
  2.     '''item is a soup item, this sub is to find all text which is in this item'''
  3.     if (item.__class__.__name__ == 'NavigableString'):
  4.         output = item.string;
  5.     else:
  6.         output = u''.join(item.findAll(text=True));
  7.     return output;

  8. def get_all_text_next_soup(item):
  9.     output = u'';
  10.     while(True):
  11.         brother = item.nextSibling;
  12.         if brother:
  13.             output = output + get_all_text_from_soup(brother);
  14.             item = brother;
  15.         else:
  16.             break;
  17.     return output;

2. 生成html

  1. from BeautifulSoup import BeautifulSoup, Tag
  2. soup = BeautifulSoup()
  3. mem_attr = ['Description', 'PhysicalID', 'Slot', 'Size', 'Width']
  4. html = Tag(soup, "html")
  5. table = Tag(soup, "table")
  6. tr = Tag(soup, "tr")
  7. soup.append(html)
  8. html.append(table)
  9. table.append(tr)
  10. for attr in mem_attr:
  11.     th = Tag(soup, "th")
  12.     tr.append(th)
  13.     th.append(attr)

  14. print soup.prettify()
另一种生成html的方法是利用pyh,这是一个很轻巧方便的途径,令人吃惊的是这个文件只有145行
# wc -l /usr/local/lib/python2.6/dist-packages/pyh.py
145 /usr/local/lib/python2.6/dist-packages/pyh.py
  1. from pyh import *
  2. page = PyH('My wonderful PyH page')
  3. page.addCSS('myStylesheet1.css', 'myStylesheet2.css')
  4. page.addJS('myJavascript1.js', 'myJavascript2.js')
  5. page << h1('My big title', cl='center')
  6. page << div(cl='myCSSclass1 myCSSclass2', id='myDiv1') << p('I love PyH!', id='myP1')
  7. mydiv2 = page << div(id='myDiv2')
  8. mydiv2 << h2('A smaller title') + p('Followed by a paragraph.')
  9. page << div(id='myDiv3')
  10. page.myDiv3.attributes['cl'] = 'myCSSclass3'
  11. page.myDiv3 << p('Another paragraph')
  12. page.printOut()
会得到如下输出
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
  2. <html lang="en" xmlns="">
  3. <head>
  4. <title>My wonderful PyH page</title>
  5. <link href="myStylesheet1.css" type="text/css" rel="stylesheet" />
  6. <link href="myStylesheet2.css" type="text/css" rel="stylesheet" />
  7. <script src="myJavascript1.js" type="text/javascript"></script>
  8. <script src="myJavascript2.js" type="text/javascript"></script>
  9. </head>
  10. <body>
  11. <h1 class="center">My big title</h1>
  12. <div id="myDiv1" class="myCSSclass1 myCSSclass2">
  13. <p id="myP1">I love PyH!>
  14. </div>
  15. <div id="myDiv2">
  16. <h2>A smaller title</h2>
  17. <p>Followed by a paragraph.</p>
  18. </div>
  19. <div id="myDiv3" class="myCSSclass3">
  20. <p>Another paragraph</p>
  21. </div>
  22. </body>
  23. </html>
项目地址为:
阅读(985) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~