码迷,mamicode.com
首页 > 编程语言 > 详细

python中用beautifulSoup+urlib2 安装、抓取和解析网页,以及解析shtml

时间:2014-10-06 01:26:49      阅读:415      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   使用   ar   sp   c   

安装 Beautiful Soup?

如果你用的是新版的Debain或ubuntu,那么可以通过系统的软件包管理来安装:

$ apt-get install Python-bs4

Beautiful Soup 4 通过PyPi发布,所以如果你无法使用系统包管理安装,那么也可以通过 easy_install 或 pip 来安装.包的名字是beautifulsoup4 ,这个包兼容Python2和Python3.

$ easy_install beautifulsoup4

$ pip install beautifulsoup4

(在PyPi中还有一个名字是 BeautifulSoup 的包,但那可能不是你想要的,那是 Beautiful Soup3 的发布版本,因为很多项目还在使用BS3, 所以 BeautifulSoup 包依然有效.但是如果你在编写新项目,那么你应该安装的 beautifulsoup4 )

如果你没有安装 easy_install 或 pip ,那你也可以 下载BS4的源码 ,然后通过setup.py来安装.

$ Python setup.py install

如果上述安装方法都行不通,Beautiful Soup的发布协议允许你将BS4的代码打包在你的项目中,这样无须安装即可使用.

作者在Python2.7和Python3.2的版本下开发Beautiful Soup, 理论上Beautiful Soup应该在所有当前的Python版本中正常工作

安装解析器?

Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .根据操作系统不同,可以选择下列方法来安装lxml:

$ apt-get install Python-lxml

$ easy_install lxml

$ pip install lxml

另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:

$ apt-get install Python-html5lib

$ easy_install html5lib

$ pip install html5lib

解析一般的网页(html),直接:

from bs4 import  BeautifulSoup,BeautifulStoneSoup

import urllib2

import html5lib

url_header = "xxxxxx"

Webpage = urllib2.urlopen(url_header).read()

soup = BeautifulSoup(webpage)

 print soup.prettify( )


但是在解析shtml的网页的时候,beautifulsoup模块支持的解释器有lxml,html5lib和HTMLparse三种,只有html5lib支持解析shtml,所以在生成beautifulsoup对象的时候,要加上一个参数:soup = BeautifulSoup(Webpage,"html5lib"),不然的话,当解析shtml页面的时候,<body> </body>标签里面的内容是无法解析的。

更多详情请参考:BeautifulSoup 4.2.0官方档http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html


python中用beautifulSoup+urlib2 安装、抓取和解析网页,以及解析shtml

标签:style   http   color   io   os   使用   ar   sp   c   

原文地址:http://my.oschina.net/u/1241293/blog/324443

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!