打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
BeautifulSoup 安装及其使用

BeautifulSoup 安装及其使用

BeautifulSoup是个好东东。

官网见这里:http://www.crummy.com/software/BeautifulSoup/

下载地址见这里:http://www.crummy.com/software/BeautifulSoup/bs4/download/4.1/附件有4.1.2的安装源码

文档见这里:http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html,是中文翻译的,不过文档有点旧,是3.0的文档版本,看起来没有什么意思。

我推荐大家看个:http://www.crummy.com/software/BeautifulSoup/bs4/doc/,这个是python的官网英文版,看起来要舒服,清晰很多。

在python下,你想按照jquery格式来读取网页,免除网页格式、标签的不规范的困扰,那么BeautifulSoup是个不错的选择。按照官网所说,BeautifulSoup是Screen-Scraping应用,旨在节省大家处理HTML标签,并且从网络中获得信息的工程。BeautifulSoup有这么几个优点,使得其功能尤其强大:

1:Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. It doesn't take much code to write an application。关键词:python风格、提供简单方法

2:Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding。关键词:编码转换,使用Python的同学都会认同Python编码格式的繁琐,BeautifulSoup能简化这一点。

3:Beautiful Soup sits on top of popular Python parsers like lxml and html5lib, allowing you to try out different parsing strategies or trade speed for flexibility。关键词:兼容其它html解析器,能够让你随心替换。

看完这几个特性,想必有人心动了吧,我们先看下BeautifulSoup的安装:

安装方法:

1:apt-get install python-bs4

2:easy_install beautifulsoup4

3:pip install beautifulsoup4

4:源码安装:python setup.py install

 

根据不同的操作系统,选用不同的安装方法,这些方法都能安装成功,不同点在于安装的工具不同。我自己的系统采用的是第四种安装方法,下面我来简要介绍下第四种安装方法:

 

Python代码  
  1. curl http://www.crummy.com/software/BeautifulSoup/bs4/download/4.1/beautifulsoup4-4.1.2.tar.gz >> beautifulsoup4-4.1.2.tar.gz  
  2. tar zxvf beautifulsoup4-4.1.2.tar.gz  
  3. cd beautifulsoup4-4.1.2  
  4. python setup.py install  
 

Ok,你就能看到安装信息,提示安装成功。

 

安装成功,肯定想迫不及待的使用,你打开python command窗口,你很happy的输入:

 

Python代码  
  1. from beautifulsoup import beautifulsoup  

 

sorry,ImportError,为什么会有这个importerror,我都安装好了的。打开官网,重新看下说明,原来安装的是BeautifulSoup 4.1版本,这个import是3.x的说法。重新打开command,输入:

 

Python代码  
  1. from bs4 import BeautifulSoup  

咦,没有输出提示。恭喜你,BeautifulSoup包引入成功。

看文上篇博客,http://isilic.iteye.com/blog/1733560,想试下dir命令,看看BeautifulSoup提供了哪些方法:

 

Python代码  
  1. dir(BeautifulSoup)  

 看到一堆的方法,有点头大,将方法列出来会方便看许多。

 

Python代码  
  1. >>> for method in dir(BeautifulSoup):  
  2. ...        print method  
  3. ...  

 

       请仔细看下其中的findXxx,nextXxx,previousXxx方法,这些方法提供了html页面的遍历、回溯、查找、匹配功能;这些功能已经能够提供获取页面信息的方法了。

我们以百度首页为例,试用下BeautifulSoup的强大功能。

 

Python代码  
  1. >>> import urllib2  
  2. >>> page=urllib2.urlopen('http://www.baidu.com')  
  3. >>> soup=BeautifulSoup(page)  
  4. >>> print soup.title  
  5. >>> soup.title.string  
 

看到结果显示不错,helloworld的教程让人心里真是舒服啊。

想进一步试用功能,我想找出百度首页上所有的链接,这个貌似很难,需要各种正则匹配,各种处理;等等,我们现在是在谈论这个BeautifulSoup,看看BeautifulSoup怎么实现这个功能。

Python代码  
  1. >>> for lind in soup.find_all('a'):  
  2. ...   print lind['href']  
  3. ...  
 

看到输出了吗?是不是很简单。

 

对于熟悉Jquery和CSS的同学,这种操作就是个折磨,需要不停的根据选择出来的结果进行遍历。看到上面的输出,看到有很多的#这些非正常的URL,现在想把这些URL全部过滤掉,使用select语法就很简单了。

Python代码  
  1. >>> for link in soup.select('a[href^=http]'):  
  2. ...   print link['href'];  
  3. ...  
 

有人说我根据判断出来的URL做处理不行嘛,当然可以,我这里只是想试下select的语法,至于select中的语法定义,大家可以自行度之。准确的说,这个select语法都能重新开篇文章了。

再进一步,连接中的/或者/duty链接都是有含义的,是相对于本站的绝对地址,这些/开头的怎么不被过滤掉?如果是绝对地址的话,又该怎么防止被过滤掉?href标签里面是个javascript又该怎么过滤?如果考虑css文件和js文件的话,怎么把这些文件的url也给找出来?还有更进一步的,怎么分析出js中ajax的请求地址?这些都是可以进一步扩展的一些要求。

好吧,我承认后面这些URL过滤已经超出了BeautifulSoup的能力范围了,但是单纯考虑功能的话,这些都是要考虑的内容,这些疑问大家考虑下实现原理就行,如果能做进一步的学习的话,算是本文额外的功劳了。

 

下面简单过下BeautifulSoup的用法:

 

Python代码  
  1. DEFAULT_BUILDER_FEATURES  
  2. FORMATTERS  
  3. ROOT_TAG_NAME  
  4. STRIP_ASCII_SPACES:BeautifulSoup的内置属性  
  5. __call__  
  6. __class__  
  7. __contains__  
  8. __delattr__  
  9. __delitem__  
  10. __dict__  
  11. __doc__  
  12. __eq__  
  13. __format__  
  14. __getattr__  
  15. __getattribute__  
  16. __getitem__  
  17. __hash__  
  18. __init__  
  19. __iter__  
  20. __len__  
  21. __module__  
  22. __ne__  
  23. __new__  
  24. __nonzero__  
  25. __reduce__  
  26. __reduce_ex__  
  27. __repr__  
  28. __setattr__  
  29. __setitem__  
  30. __sizeof__  
  31. __str__  
  32. __subclasshook__  
  33. __unicode__  
  34. __weakref__  
  35. _all_strings  
  36. _attr_value_as_string  
  37. _attribute_checker  
  38. _feed  
  39. _find_all  
  40. _find_one  
  41. _lastRecursiveChild  
  42. _last_descendant  
  43. _popToTag:BeautifulSoup的内置方法,关于这些方法使用需要了解Python更深些的内容。  
  44. append:修改element tree  
  45. attribselect_re  
  46. childGenerator  
  47. children  
  48. clear:清除标签内容  
  49. decode  
  50. decode_contents  
  51. decompose  
  52. descendants  
  53. encode  
  54. encode_contents  
  55. endData  
  56. extract:这个方法很关键,后面有介绍  
  57. fetchNextSiblings下一兄弟元素  
  58. fetchParents:父元素集  
  59. fetchPrevious:前一元素  
  60. fetchPreviousSiblings:前一兄弟元素:这几个能够对当前元素的父级别元素和兄弟级别进行查找。  
  61. find:只找到limit为1的结果  
  62. findAll  
  63. findAllNext  
  64. findAllPrevious  
  65. findChild  
  66. findChildren:子集合  
  67. findNext:下一元素  
  68. findNextSibling:下一个兄弟  
  69. findNextSiblings:下一群兄弟  
  70. findParent:父元素  
  71. findParents:所有的父元素集合  
  72. findPrevious  
  73. findPreviousSibling  
  74. findPreviousSiblings:对当前元素和子元素进行遍历查找。  
  75. find_all_next  
  76. find_all_previous  
  77. find_next  
  78. find_next_sibling  
  79. find_next_siblings  
  80. find_parent  
  81. find_parents  
  82. find_previous  
  83. find_previous_sibling  
  84. find_previous_siblings:这些下划线方法命名是bs4方法,推荐使用这类  
  85. format_string  
  86. get  
  87. getText  
  88. get_text:得到文档标签内的内容,不包括标签和标签属性  
  89. handle_data  
  90. handle_endtag  
  91. handle_starttag  
  92. has_attr  
  93. has_key  
  94. index  
  95. insert  
  96. insert_after  
  97. insert_before:修改element tree  
  98. isSelfClosing  
  99. is_empty_element  
  100. new_string  
  101. new_tag  
  102. next  
  103. nextGenerator  
  104. nextSibling  
  105. nextSiblingGenerator  
  106. next_elements  
  107. next_siblings  
  108. object_was_parsed  
  109. parentGenerator  
  110. parents  
  111. parserClass  
  112. popTag  
  113. prettify:格式化HTML文档  
  114. previous  
  115. previousGenerator  
  116. previousSibling  
  117. previousSiblingGenerator  
  118. previous_elements  
  119. previous_siblings  
  120. pushTag  
  121. recursiveChildGenerator  
  122. renderContents  
  123. replaceWith  
  124. replaceWithChildren  
  125. replace_with  
  126. replace_with_children:修改element tree 元素内容  
  127. reset  
  128. select:适用于jquery和css的语法选择。  
  129. setup  
  130. string  
  131. strings  
  132. stripped_strings  
  133. tag_name_re  
  134. text  
  135. unwrap  
  136. wrap  

 

 

需要注意的是,在BeautifulSoup中的方法有些有两种写法,有些是驼峰格式的写法,有些是下划线格式的写法,但是看其方法的含义是一样的,这主要是BeautifulSoup为了兼容3.x的写法。前者是3.x的写法,后者是4.x的写法,推荐使用后者,也就是下划线的方法。

 

根据这些方法,应该能够得到遍历、抽取、修改、规范化文档的一系列方法。大家如果能在工作中使用BeautifulSoup,一定会理解更深。

 

BeautifulSoup支持不同的parser,默认是Html 格式解析,还有xmlparser、lxml parser、html5lib parser、html.parser,这些parser都需要响应的解析器支持。

 html,这个是默认的解析器

Python代码  
  1. BeautifulSoup("<a><b /></a>")  
  2. # <html><head></head><body><a><b></b></a></body></html>  
 

 xml格式解析器

Python代码  
  1. BeautifulSoup("<a><b /></a>", "xml")  
  2. # <?xml version="1.0" encoding="utf-8"?>  
  3. # <a><b /></a>  
 

 lxml格式解析器

Python代码  
  1. BeautifulSoup("<a></p>", "lxml")  
  2. # <html><body><a></a></body></html>  
 

 html5lib格式解析器

Python代码  
  1. BeautifulSoup("<a></p>", "html5lib")  
  2. # <html><head></head><body><a><p></p></a></body></html>  
 

 html.parser解析器

Python代码  
  1. BeautifulSoup("<a></p>", "html.parser")  
  2. # <a></a>  
 

 

其中parser的区别大家看下这几个例子就知道了。

 

在使用BeautifulSoup解析文档的时候,会将整个文档以一颗大又密集的数据载入到内存中,如果你只是从数据结构中获得一个字符串,内存中保存一堆数据感觉就不划算了。并且如果你要获得指向某个Tag的内容,这个Tag又会指向其它的Tag对象,因此你需要保存这棵树的所有部分,也就是说整棵树都在内存中。extract方法可以破坏掉这些链接,它会将树的连接部分断开,如果你得到某个Tag,这个Tag的剩余部分会离开这棵树而被垃圾收集器捕获;当然,你也可以实现其它的功能:如文档中的某一块你本身就不关心,你可以直接把它extract出树结构,扔给垃圾收集器,优化内存使用的同时还能完成自己的功能。

 

正如BeautifulSoup的作者Leonard所说,写BeautifulSoup是为了帮助别人节省时间,减小工作量。一旦习惯使用上BeautifulSoup后,一些站点的内容很快就能搞定。这个就是开源的精神,将工作尽可能的自动化,减小工作量;从某个程度上来说,程序员应该是比较懒惰的,但是这种懒惰正好又促进了软件行业的进步。

 

 

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python之Html解析方法
python爬虫beautifulsoup4系列4-子节点​
Python 爬虫(三):BeautifulSoup 库
如何利用Python爬取网络小说
python BeautifulSoup 抓取网页内指定内容
爬虫入门:如何用python爬取网易新闻?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服