详细的内容请看这里——参考博客,下面是自己需要参考的部分总结。
- 创建 Beautiful Soup 对象,首先必须要导入 bs4 库
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>
"""
- 创建 beautifulsoup 对象
soup = BeautifulSoup(html)
- Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:Tag、NavigableString、BeautifulSoup、Comment。
(1) Tag:Tag 是什么?通俗点讲就是 HTML 中的一个个标签,例如head,title,a,p等,注释为输出。
print soup.title
#<title>The Dormouse's story</title>
print soup.head
#<head><title>The Dormouse's story</title></head>
print soup.a
#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
print soup.p
#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
它有两个属性,name和attrs,使用如下。
#name到没什么,主要在sttrs。
print soup.name #[document]
print soup.head.name #head
print soup.p.attrs
#{'class': ['title'], 'name': 'dromouse'}
print soup.p['class'] #['title']
(2)NavigableString:获取标签内的字符串。
print soup.p.string
#The Dormouse's story
(3)BeautifulSoup:
(4)Comment
- 遍历文档树,.contents .children 属性。
print soup.head.contents
#[<title>The Dormouse's story</title>]
print soup.head.contents[0]#会以列表的形式出书。
#<title>The Dormouse's story</title>
- CSS选择器,我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list。
print soup.select('title')
#[<title>The Dormouse's story</title>]
print soup.select('a')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
print soup.select('.sister')#通过类名查找
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
print soup.select('#link1')#通过id查找
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
#组合查找,二者需要用空格分开
print soup.select('p #link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
print soup.select("head > title")
#[<title>The Dormouse's story</title>]
#属性查找,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,
print soup.select('p a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]