bs4模块

一、导入模块

  from bs4 import BeautifulSoup

二、创建对象

  Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。

解析器使用方法优势劣势
Python标准库 BeautifulSoup(markup, "html.parser")
  • Python的内置标准库
  • 执行速度适中
  • 文档容错能力强
  • Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
lxml HTML 解析器 BeautifulSoup(markup, "lxml")
  • 速度快
  • 文档容错能力强
  • 需要安装C语言库
lxml XML 解析器

BeautifulSoup(markup, ["lxml-xml"])

BeautifulSoup(markup, "xml")

  • 速度快
  • 唯一支持XML的解析器
  • 需要安装C语言库
html5lib BeautifulSoup(markup, "html5lib")
  • 最好的容错性
  • 以浏览器的方式解析文档
  • 生成HTML5格式的文档
  • 速度慢
  • 不依赖外部扩展
html = """
<html>
<head><title>A Tale of Two Cities</title></head>
<body>
<p class="title" name="dromouse"><b>A Tale of Two Cities</b></p>
<p class="story">
It was the best of times;It was the worst of times. <a href="http://example.com/age" class="of" id="link1">It was the age of wisdom;it was the age of foolishness </a>.
<a href="http://example.com/epoch" class="of" id="link2">It was the epoch of belief;it was the epoch of incredulity </a>.
<a href="http://example.com/season" class="of" id="link3">It was the season of Light;it was the season of Darkness </a>.
It was the spring of hope;it was the winter of despair.
</p> <h2 class="story"> <!-- This is comment --> </h2>
<h3 class="hey"> Hey<!-- Now --> </h3>
<h4>Well Done</h4>
</body> </html>
""" soup = BeautifulSoup(html, features="lxml") #另外,我们还可以用本地 HTML 文件来创建对象,例如 soup = BeautifulSoup(open('index.html'), features="lxml") #上面这句代码便是将本地 index.html 文件打开,用它来创建 soup 对象

三、对象的方法属性调用

1、对象

  Beautiful Soup 将复杂HTML文档转换成一个复杂的树形结构,每个节点都是 Python 对象。

import bs4
html = """
<html>
    <head><title>A Tale of Two Cities</title></head>
    <body>
        <h1 class="title" name="dromouse">
            进程
            <b>线程  <a href="http://example.com/epoch">协程</a>   </b>
            <b>基础  <a href="http://example.com/epoch">  <i>自动化</i>  </a>  </b>
            运算
            <a href="http://example.com/epoch">流程</a>
            模块           
        </h1>
        <h3 class="hey"> 看看<!-- 嘿嘿 --> </h3>
    </body>
</html>
"""  
soup = BeautifulSoup(html, features="lxml")     #soup本身就是一个document标签

#每个tag都有自己的名字:
print(soup.name)

#一个tag可能有很多个属性:
print(soup.attrs)

#一个tag的属性值可以有一个,也可以多个,最常见的多值的属性是 class (一个tag可以有多个CSS的class). 
print(soup.meta['class'])                             #等效于print(soup.meta.get('class'))
print(soup.meta.get_attribute_list('class'))

css_soup = BeautifulSoup('<p class="body strikeout">123</p>')
css_soup.p['class']
# ["body", "strikeout"]

#获取tag的所有内容,包括其子标签的内容
for i in soup:
    print(i)                                       #打印标签里所有内容,包括子标签的标记符号和属性,文本内容等等。等效于print(soup.get_text)

print(soup.getText())                              #等效于print(soup.get_text()) 或者print(soup.text),打印本身标签及其子标签的文本内容
print(soup.getText)                                #等效于print(soup.get_text)    

#.string只有a标签里没有子标签才可以输出本身的文本内容
print(soup.h1.b.a.string)

#.strings可以遍历输出标签里的所有文本内容,包括子标签的文本内容
for i in soup.h1.strings:
    print(i)

2、遍历对象--文档树

 (1)子节点

#.contents 可以将tag的子节点以列表的方式输出,仅包含tag的直接子节点
#.children可以将tag的子节点以列表迭代器对象的方式输出,仅包含tag的直接子节点

print(soup.h1.children)
#输出<list_iterator object at 0x7f7e395416a0>

for i in soup.h1.children:
    print(i)

遍历子节点输出

            进程
            
<b>线程  <a href="http://example.com/epoch">协程</a> </b>


<b>基础  <a href="http://example.com/epoch"> <i>自动化</i> </a> </b>

            运算
            
<a href="http://example.com/epoch">流程</a>

            模块           
        

(2)父节点

通过 .parent 属性来获取某个元素的父节点

print(soup.b.parent)

输出

<h1 class="title" name="dromouse">
            进程
            <b>线程  <a href="http://example.com/epoch">协程</a> </b>
<b>基础  <a href="http://example.com/epoch"> <i>自动化</i> </a> </b>
            运算
            <a href="http://example.com/epoch">流程</a>
            模块           
        </h1>

通过元素的 .parents 属性可以递归得到元素的所有父辈节点

(3)兄弟节点

前一个兄弟节点

for i in soup.a.previous_siblings:
    print(i)

#输出:线程

下一个兄弟节点

for i in soup.b.next_siblings:
    print(i)

输出

<b>基础  <a href="http://example.com/epoch"> <i>自动化</i> </a> </b>

            运算
            
<a href="http://example.com/epoch">流程</a>

            模块      

(4)元素节点

print(soup.h1.next_element)
#输出:进程

print(soup.a.previous_element)
#输出:线程

3、搜索文档树

 1)、find_all( name , attrs , recursive , text , **kwargs )

#传字符串
'''最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup 会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的 标签'''
soup.find_all('b')
#传正则表达式
'''如果传入正则表达式作为参数,Beautiful Soup 会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示 和 标签都应该被找到'''
soup.find_all(re.compile("^b"))
#传列表
'''如果传入列表参数,Beautiful Soup 会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有 <a> 标签和 <b> 标签'''
soup.find_all(["a", "b"])
#传 True
'''True 可以匹配任何值,下面代码查找到所有的 tag,但是不会返回字符串节点'''
soup.find_all(True)
#传方法
'''如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 [4] ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性,那么将返回 True'''
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)
#keyword 参数
'''注意:如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字 tag 的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup 会搜索每个 tag 的 ”id” 属性
soup.find_all(id='link2')
如果传入 href 参数,Beautiful Soup 会搜索每个 tag 的 ”href” 属性
soup.find_all(href=re.compile("elsie"))
使用多个指定名字的参数可以同时过滤 tag 的多个属性
soup.find_all(href=re.compile("elsie"), id='link1')
在这里我们想用 class 过滤,不过 class 是 python 的关键词,这怎么办?加个下划线就可以
soup.find_all("a", class_="sister")
有些 tag 属性在搜索不能使用,比如 HTML5 中的 data-* 属性
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
data_soup.find_all(data-foo="value")
# SyntaxError: keyword can't be an expression  
但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag
data_soup.find_all(attrs={"data-foo": "value"})'''
#text 参数
'''通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True
soup.find_all(text="Elsie")'''
#limit 参数
'''find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与 SQL 中的 limit 关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.
文档树中有3个 tag 符合搜索条件,但结果只返回了2个,因为我们限制了返回数量
soup.find_all("a", limit=2)'''
#recursive 参数
'''调用 tag 的 find_all() 方法时,Beautiful Soup 会检索当前 tag 的所有子孙节点,如果只想搜索 tag 的直接子节点,可以使用参数 recursive=False。'''
参数分析

 2)、find( name , attrs , recursive , text , **kwargs )

 3)、find_parents() fin_parent()

 4)、find_next_siblings() find_next_sibling()

 5)、find_previous_siblings() find_previous_sibling()

 6)、find_all_next() find_next()

7)、find_all_previous() 和 find_previous()

4、css选择器

我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加#,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list。

1)、通过标签名查找

print soup.select('title') 
#[<title>The Dormouse's story</title>]

2)、通过类名查找

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>] 

3)、通过 id 名查找

print soup.select('#link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>] 

4)、组合查找

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

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>]  

5)、属性查找

查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。

print soup.select('a[class="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('a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]  
#同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格
print soup.select('p a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]  

 

posted @ 2019-04-28 18:36  Einewhaw  阅读(931)  评论(0编辑  收藏  举报