2016-04-20 01:05:07| 分类: Web技术-Python | 标签: |举报 |字号大中小 订阅
–官网:http://www.crummy.com/software/BeautifulSoup/
–官方文档:http://www.crummy.com/software/BeautifulSoup/bs4/doc/
安装方式:
如果你用的是新版的Debain或ubuntu,那么可以通过系统的软件包管理来安装:
$ apt-get install Python-bs4
Beautiful Soup 4 通过PyPi发布,所以如果你无法使用系统包管理安装,那么也可以通过 easy_install 或 pip 来安装.包的名字是 beautifulsoup4 ,这个包兼容Python2和Python3.
$ easy_install beautifulsoup4
$ pip install beautifulsoup4
如果你没有安装 easy_install 或 pip ,那你也可以 下载BS4的源码 (此方式也适用于window上安装) ,然后通过setup.py来安装.
$ Python setup.py install
安装完成后,在python中import bs4,如果没有报错,则证明安装成功。我们便可以开始愉快的beautifulsoup之旅啦。
在window下载bs4包减压后,放到python的安装目录。
然后在命令行模式下,进人beautifulsoup目录,如:D:\intall\python2.7\beautifulsoup4-4.1.0,执行:
setup.py install
若出现如下见面:
则说明安装成功。
在代码中,我们导入即可:
from bs4 import BeautifulSoup #注意这里bs4
如何使用:
# -*- coding:utf-8 -*-
#导入所需要的模块
from bs4 import BeautifulSoup
import re
#一段html的字符串
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
#创建beautifulsoup对象
soup = BeautifulSoup(html_doc, 'html.parser',
from_encoding = 'utf-8')
#查找html文档中出现的所有链接
print '获取所有的链接:'
links = soup.find_all('a')
for link in links:
print link.name, link['href'], link.get_text()
#查找html文档中lacie的链接
print '获取lacie的链接:'
link_node = soup.find('a', href = 'http://example.com/lacie')
print link_node.name, link_node['href'], link_node.get_text()
#利用正则表达式进行模糊匹配
print '正则模糊匹配:'
link_node = soup.find('a', href = re.compile(r"ill"))
print link_node.name, link_node['href'], link_node.get_text()
#获取标题的文字
print '获取p段落文字:'
link_node = soup.find('p', class_ = "title")
print link_node.name, link_node.get_text()
源:http://www.guolanzhe.com/?p=133
评论