8586231_192932724000_2.jpg
beautifulsoup模块简介
- 相比于xpath表达式,BeautifulSoup较有难度,同样的它的一些用法更为方便,所以是与爬虫解析基础的正则表达式、xpath相互配合使用的。
- 和lxml 一样,BeautifulSoup 也是一个HTML/XML的解析器。
- 主要的功能也是如何解析和提取 HTML/XML 数据。
模块下载方法
- pip install bs4
基础用法
__author__ = 'Administrator'
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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>
"""
#解析字符串形式的html
soup=BeautifulSoup(html,'lxml')
#格式化输出soup对象
print(soup.prettify())#prettify方法将html文档以标准的(漂亮的)方式输出。
#解析本地的html
# soup1=BeautifulSoup(open('index.html'))
# print(soup1)