解析库beautifulsoup

解析库beautifulsoup的介绍

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库

#安装 Beautiful Soup
pip install beautifulsoup4

#安装解析器
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .根据操作系统不同,可以选择下列方法来安装lxml:

pip install lxml

下表列出了主要的解析器,以及它们的优缺点,官网推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib, 因为那些Python版本的标准库中内置的HTML解析方法不够稳定.

解析器使用方法优势劣势
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格式的文档
  • 速度慢
  • 不依赖外部

中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

bs4的使用

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id="id_p"><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>
"""

# pip3 install lxml
soup=BeautifulSoup(html_doc,'lxml')
# 美化
print(soup.prettify())

# 遍历文档树

# 1.用法(通过.来查找,只能找到第一个)
head = soup.head  # Tag对象
title = head.title
print(head)
print(title)

print(soup.p)  # 因为有多个p,所以只能找到第一个

# 2.获取标签的名称
b = soup.body
print(b.name)

# 3.获取标签的属性
# 方式一
print(soup.p['class'])  # class因为可以有多个,所以获取的是个列表
print(soup.p['id'])
# 方式二
print(soup.p.attrs['class'])
print(soup.p.attrs.get('id'))

# 4.获取标签的内容
print(soup.p.string) # p下的文本只有一个时能取到, 否则为None
print(list(soup.p.strings)) #拿到一个生成器对象, 取到p下所有的文本内容
print(soup.p.text) #取到p下所有的文本内容

# 5.嵌套选择
title=soup.head.title
print(title)

# 6.子节点、子孙节点
p1=soup.p.children   # 迭代器
p2=soup.p.contents  # 列表
print(list(p1))
print(p2)

# 7.父节点、祖先节点
print(soup.p.parent)  # 父节点
print(list(soup.p.parents)) # 生成器

# 8.兄弟节点
print(soup.a.next_sibling) #下一个兄弟
print(soup.a.previous_sibling) #上一个兄弟

print(list(soup.a.next_siblings)) #下面的兄弟们=>生成器对象
print(soup.a.previous_siblings) #上面的兄弟们=>生成器对象


# 搜索文档树(find,find_all),速度比遍历文档树慢
# 两个配合着使用(soup.p.find())
"""
find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果.
find_all() 方法没有找到目标是返回空列表, find() 方法找不到目标时,返回 None .
"""
# 五种过滤器: 字符串、正则表达式、列表、True、方法
# 以find为例
# 一、字符串查找 字符串:即标签名
b=soup.find(name='body')
print(b)

# 查找类名是title的所有标签 class_
print(soup.find_all(class_='title'))
# 找href为http://example.com/elsie的标签
print(soup.find_all(href='http://example.com/elsie'))

# 二、正则表达式
import re
reg = re.compile('^b')
print(soup.find_all(name=reg))

# 三、列表
# ret=soup.find_all(name=['body','b'])
# ret=soup.find_all(id=['id_p','link1'])
# ret=soup.find_all(class_=['id_p','link1'])
# and 关系
ret=soup.find_all(class_='title',name='p')
print(ret)

# 四、True
# 所有有id的标签
print(soup.find_all(id=True))

# 五、方法
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

print(soup.find_all(has_class_but_no_id))

# 六、其他使用
ret=soup.find_all(attrs={'class':"title"})
print(ret)

# 七、拿到标签,取属性,取text
ret=soup.find_all(attrs={'id':"id_p",'class':'title'})
print(ret[0].text)

# 八、limit:参数限制返回结果的数量
# soup.find()  其实就是find_all limit=1
ret=soup.find_all(name=True,limit=2)
print(len(ret))

# 九、recursive:调用tag的find_all()方法时,会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数recursive=False
ret=soup.body.find_all(name='p',recursive=False)
print(ret)

bs4的css选择器

 注意:

Tag对象.select("css选择器")

例如:
#ID号
.类名
div>p:儿子 和div p:子子孙孙
找div下最后一个a标签 div a:last-child

bs4:有自己的选择器,css选择器
lxml:css选择器,xpath选择器
selenium:自己的选择器,css选择器,xpath选择器
scrapy框架:自己的选择器,css选择器,xpath选择器
#该模块提供了select方法来支持css,详见官网:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id37
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title">
    <b>The Dormouse's story</b>
    Once upon a time there were three little sisters; and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">
        <span>Elsie</span>
    </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>;
    <div class='panel-1'>
        <ul class='list' id='list-1'>
            <li class='element'>Foo</li>
            <li class='element'>Bar</li>
            <li class='element'>Jay</li>
        </ul>
        <ul class='list list-small' id='list-2'>
            <li class='element'><h1 class='yyyy'>Foo</h1></li>
            <li class='element xxx'>Bar</li>
            <li class='element'>Jay</li>
        </ul>
    </div>
    and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml')

#1、CSS选择器
print(soup.p.select('.sister'))
print(soup.select('.sister span'))

print(soup.select('#link1'))
print(soup.select('#link1 span'))

print(soup.select('#list-2 .element.xxx'))

print(soup.select('#list-2')[0].select('.element')) #可以一直select,但其实没必要,一条select就可以了

# 2、获取属性
print(soup.select('#list-2 h1')[0].attrs)

# 3、获取内容
print(soup.select('#list-2 h1')[0].get_text())

 

posted @ 2020-04-08 21:27  Hank·Paul  阅读(218)  评论(0编辑  收藏  举报