Python_Beautiful Soup 使用介绍

一. Beautiful Soup 使用介绍

  • Beautiful Soup 是Python的一个HTML或XML的解析库,可方便处理导航、搜索、修改分析树等功能。通过解析文档为用户提供需要提取的数据,可以用少量代码就可以写出一个完整的应用程序。
  • Beautiful Soup 自动将输入文档转换为 Unicode 编码,输出文档转换为 UTF-8 编码。
    你不需妥考虑、编码方式,除非文档没有指定编码方式,这时你仅需说明原始编码方式即可。
  • Beautiful Soup 已成为和lxml、 html6lib一样出色的 Python 解释器,为用户灵活地提供不同的解析策略或强劲的速度。

二. 安装 Beautiful Soup 和 lxml

按Windows+R组合键,在运行窗口输入cmd进入命令提示符窗口

pip3 install beautifulsoup4
pip3 install lxml

三. Beautiful Soup 支持的解析器

  • Python 标准库
    用法:BeautifulSoup(markup,‘html.parser’)
    优势:Python 的内宜标准库、执行 速度适中、文档容错能力强
    劣势:Python 2.7.3及 Python 3.2.2 之前的版本文档容错能力差
  • lxml HTML 解析器
    用法: BeautifulSoup(markup,‘lxml’)
    优势:速度快、文档容错能力强
    劣势:需要安装C语言库
  • lxml XML 解析器
    用法:BeautifulSoup(markup,‘xml’)
    优势:速度快、唯一支持 XML的解析器
    缺点:需要安装C语言库
  • html5lib
    用法: BeautifulSoup(markup,‘htmlSlib’)
    优势:最好的容错性、以浏览器的方式解析文梢、生成 HTML5 扩展格式的文档.
    缺点:速度慢,不依赖外部扩展

四. Beautiful Soup使用示例

from bs4 import BeautifulSoup
from lxml import etree
import re
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>
<div data-foo="value">foo!</div>
'''
soup = BeautifulSoup(html,'lxml')

1.格式化输出

print(soup.prettify())

2.获取title标签/标签内文本

print(soup.title)
print(soup.title.text)

#<title>The Dormouse's story</title>
#The Dormouse's story

3.获取a标签(只打印第1个节点)

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

4. 获取Tag标签内容

soup加标签名轻松地获取这些标签的内容,但它查找的是在所有内容中的第一个符合要求的标签

4.1 Tag属性 name

print(soup.name)
print(soup.head.name)
#结果:[document]
#结果:head

4.2 Tag属性 attrs

print(soup.p)
print(soup.p['class'])
#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
#['title']

4.3 获取标签内部的文字,用.string

#如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。
#如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容
#如果tag包含了多个子节点,tag就无法确定,string 方法应该调用哪个子节点的内容, .string 的输出结果是 None

print(soup.p.string)
#The Dormouse's story
 
print(soup.html.string)
#None

5. contents属性可以将tag 的子节点以列表形式输出

print(soup.head.contents)

6.所有的子节点,遍历输出

for child in soup.body.children:
   print(child)

7 搜索文档

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

#find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件
#1.1name 参数:name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉

A.传字符串

#最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,
#下面的例子用于查找文档中所有的标签

print(soup.find_all('b'))
#>>>[<b>The Dormouse's story</b>]
B.传正则表达式

#如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.
#下面例子中找出所有以b开头的标签,这表示和标签都应该被找到

import re
for tag in soup.find_all(re.compile('b')):
    print(tag.name)
#>>> body
#>>> b
C.传列表

如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.
下面代码找到文档中所有<a> 标签和<b>标签

print(soup.find_all(['a','b']))
D.传 True

True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点

for tag1 in soup.find_all(True):
    print(tag1.name)
E.传方法

#如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数
#如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False

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)
#输出结果:
#[<p class="title"><b>The Dormouse's story</b></p>,
#<p class="story">Once upon a time there were...</p>,
#<p class="story">...</p>]

2、keyword 参数

注意:如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的"id"属性

print(soup.find_all(id='link2'))
#>>> [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

#如果传入 href 参数,Beautiful Soup会搜索每个tag的"href"属性
print(soup.find_all(href=re.compile("elsie")))
#>>> [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

#使用多个指定名字的参数可以同时过滤tag的多个属性
print(soup.find_all(href=re.compile("elsie"), id='link1'))
#>>> [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]

#在这里我们想用 class 过滤,不过 class 是 python 的关键词,加个下划线 Class_ 就可以
print(soup.find_all("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>]

#有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>','lxml')
#print data_soup.find_all(data-foo="value")
#SyntaxError: keyword can't be an expression
print(soup.find_all(attrs={'data-foo':'value'}))

#但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag
print(soup.find_all(attrs={"data-foo": "value"}))
#[<div data-foo="value">foo!</div>]

3 text 参数

print(soup.find_all(text="Elsie"))
#[u'Elsie']

print(soup.find_all(text=["Tillie", "Elsie", "Lacie"]))
#[u'Elsie', u'Lacie', u'Tillie']

print( soup.find_all(text=re.compile("Dormouse")))
#>>> [u"The Dormouse's story", u"The Dormouse's story"]

4. limit 参数

find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.
效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.

print(soup.find_all("a", limit=2))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

3、CSS选择器

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

3.1通过标签名查找
print(soup.select('title'))
#[<title>The Dormouse's story</title>]
3.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.3 通过 id 名查找
print(soup.select('#link1'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
3.4 组合查找

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

print(soup.select('p #link1'))
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
3.5 直接子标签查找
print(soup.select("head > title"))
#[<title>The Dormouse's story</title>]
3.6 属性查找

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

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

以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容。

soup = BeautifulSoup(html, 'lxml')
print(type(soup.select('title')))
print(soup.select('title')[0].get_text())
 
for title in soup.select('title'):
    print(title.get_text())

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值