---
title: "python-bs4->Beautiful Soup的用法"
author: "xwins"
date: "2016-08-16T13:43:32Z"
tags: []
categories: ["编程语言"]
slug: "python-bs4-beautiful-soup"
draft: false
lastmod: "2016-08-16T14:12:32Z"
id: 2317710
url: "https://886.iteye.com/blog/2317710"
---

# 1.安装

pip install beautifulsoup4

或者

python setup.py install（附件）

# 2.介绍

解析（markup为html文件内容）

BeautifulSoup(markup, “html.parser”)-》Python 2.7.3以上

BeautifulSoup(markup, “lxml”)-》速度快

BeautifulSoup(markup, “html5lib”)-》容错性好，速度慢from bs4

# 3.举例

import BeautifulSoup 

soup = BeautifulSoup(html) 

#soup = BeautifulSoup(open('index.html')) 

print soup.prettify()#格式化 

# 4.使用

 

## 1.TAG

html1='&lt;head&gt;&lt;title&gt;The Dormouse's story&lt;/title&gt;&lt;/head&gt;' 

soup = BeautifulSoup(html1) 

print soup.title 

#&lt;title&gt;The Dormouse's story&lt;/title&gt;#仅仅取第一条 

print soup.head 

#&lt;head&gt;&lt;title&gt;The Dormouse's story&lt;/title&gt;&lt;/head&gt; 

## 2.attrs

html2='&lt;p class="title" name="dromouse"&gt;&lt;b&gt;The Dormouse's story&lt;/b&gt;&lt;/p&gt;' 

soup = BeautifulSoup(html2) 

print soup.p.attrs 

#{'class': \['title'], 'name': 'dromouse'} 

print soup.p\['class'] 

#\['title'] 

print soup.p.get('class') 

#\['title'] 

## 3.string

print soup.p.string 

#The Dormouse's story  

## 4.Comment

无注释的文本

html3='&lt;a class="sister" href="http://example.com/elsie" id="link1"&gt;&lt;!-- Elsie --&gt;&lt;/a&gt;' 

soup = BeautifulSoup(html2) 

if type(soup.a.string)==bs4.element.Comment: 

    print soup.a.string 

## 5.contents

print soup.head.contents #打印子节点，为list集合 

#\[&lt;title&gt;The Dormouse's story&lt;/title&gt;] 

## 6.children

for child in  soup.body.children:#list生成器子节点 

    print child 

## 7.descendants

for child in soup.descendants:#递归打印所有子节点 

    print child

## 8.stripped\_strings

for string in soup.stripped\_strings:#子节点下所有string，且去除换行符等空白 

    print(repr(string)) 

    # u"The Dormouse's story" 

    # u"The Dormouse's story" 

    # u'Once upon a time there were three little sisters

## 9.parent parents

p = soup.p#父节点 

print p.parent.name 

#body&lt;/strong&gt; 

## 10.find\_all( name , attrs , recursive , text , \*\*kwargs )

### 1）name-tag内容

A.传字符串

soup.find\_all('b')

\# \[&lt;b&gt;The Dormouse's story&lt;/b&gt;]

B.传正则表达式

import re

for tag in soup.find\_all(re.compile("^b")):

print(tag.name)

\# body

\# b

C.传列表

soup.find\_all(\["a","b"])

\# [&lt;b&gt;The Dormouse's story&lt;/b&gt;,

#&lt;a href="http://example.com/elsie" id="link1"&gt;Elsie&lt;/a&gt;,

#&lt;a href="http://example.com/lacie" id="link2"&gt;Lacie&lt;/a&gt;]

 

D.传 True

True 可以匹配任何值,但是不会返回字符串节点

For tag in soup.find\_all(True):

    print(tag.name)

\# html

\# head

\# title

\# body

\# p

E.传方法

def has\_class\_but\_no\_id(tag):

    return tag.has\_attr('class') and not tag.has\_attr('id')

soup.find\_all(has\_class\_but\_no\_id)

\# [&lt;p class="title"&gt;&lt;b&gt;The Dormouse's story&lt;/b&gt;&lt;/p&gt;,

#  &lt;p class="story"&gt;Once upon a time there were...&lt;/p&gt;,

#  &lt;p class="story"&gt;...&lt;/p&gt;]

### 2）keyword

soup.find\_all(id='link2')

\# \[&lt;a href="http://example.com/lacie" id="link2"&gt;Lacie&lt;/a&gt;]

soup.find\_all(href=re.compile("elsie"))

\# \[&lt;a href="http://example.com/elsie" id="link1"&gt;Elsie&lt;/a&gt;]

soup.find\_all(href=re.compile("elsie"), id='link1')

\# \[&lt;a href="http://example.com/elsie" id="link1"&gt;three&lt;/a&gt;]

Class为关键字，需加下划线

soup.find\_all("a", class\_="sister")

有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性

data\_soup.find\_all(attrs={"data-foo": "value"})

\# \[&lt;div data-foo="value"&gt;foo!&lt;/div&gt;]

### 3）text 参数

通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True

soup.find\_all(text="Elsie")

\# \[u'Elsie']

soup.find\_all(text=\["Tillie", "Elsie", "Lacie"])

\# \[u'Elsie', u'Lacie', u'Tillie']

soup.find\_all(text=re.compile("Dormouse"))

\[u"The Dormouse's story", u"The Dormouse's story"]

### 4）limit 参数

当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.

soup.find\_all("a", limit=2)

\# [&lt;a href="http://example.com/elsie" id="link1"&gt;Elsie&lt;/a&gt;,

#  &lt;a href="http://example.com/lacie" id="link2"&gt;Lacie&lt;/a&gt;]

### 5）recursive 参数

调用tag的 find\_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .

## 11.find( name , attrs , recursive , text , \*\*kwargs )

它与 find\_all() 方法唯一的区别是 find\_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果

## 12.find\_parents()  find\_parent()

## 13.CSS选择器select

soup.select()，返回类型是 list

### （1）通过标签名查找

print soup.select('title')

#\[&lt;title&gt;The Dormouse's story&lt;/title&gt;]

print soup.select('a')

### （2）通过类名查找

print soup.select('.sister')

#\[&lt;a class="sister" href="http://example.com/elsie" id="link1"&gt;&lt;!-- Elsie --&gt;&lt;/a&gt;, &lt;a class="sister" href="http://example.com/lacie" id="link2"&gt;Lacie&lt;/a&gt;, &lt;a class="sister" href="http://example.com/tillie" id="link3"&gt;Tillie&lt;/a&gt;]

### （3）通过 id 名查找

print soup.select('#link1')

#\[&lt;a class="sister" href="http://example.com/elsie" id="link1"&gt;&lt;!-- Elsie --&gt;&lt;/a&gt;]

### （4）组合查找

组合查找即和写 class 文件时，标签名与类名、id名进行的组合原理是一样的，例如查找 p 标签中，id 等于 link1的内容，二者需要用空格分开

print soup.select('p #link1')

#\[&lt;a class="sister" href="http://example.com/elsie" id="link1"&gt;&lt;!-- Elsie --&gt;&lt;/a&gt;]

### （5）直接子标签查找

print soup.select("head &gt; title")

#\[&lt;title&gt;The Dormouse's story&lt;/title&gt;]

### （6）属性查找

print soup.select('a\[class="sister"]')

#\[&lt;a class="sister" href="http://example.com/elsie" id="link1"&gt;&lt;!-- Elsie --&gt;&lt;/a&gt;, &lt;a class="sister" href="http://example.com/lacie" id="link2"&gt;Lacie&lt;/a&gt;, &lt;a class="sister" href="http://example.com/tillie" id="link3"&gt;Tillie&lt;/a&gt;]

### （7）通配符

print soup.select('a\[class\*="sister"]')#包含sister

print soup.select('a\[class$="sister"]')# sister结尾

print soup.select('a\[class^="sister"]') # sister开头