解析库

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

基本使用

html = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<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">
<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>
and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify())
print(soup.title.string)

标签选择器

选择元素

print(soup.title)
print(type(soup.title))
print(soup.head)
print(soup.p)

获取名称

print(soup.title.name)

title

获取属性

print(soup.p.attrs['name'])
print(soup.p['name'])

dromouse

dromouse

获取内容

print(soup.p.string)

The Dormouse's story

嵌套选择

print(soup.head.title.string)

The Dormouse's story

子节点和子孙节点

print(soup.p.contents)

['\n Once upon a time there were three little sisters; and their names were\n ', Elsie, '\n', Lacie, ' \n and\n ', Tillie, '\n and they lived at the bottom of a well.\n ']

print(soup.p.children)
for i,child in enumerate(soup.p.children):
print(i,child)

父节点和祖先节点

print(soup.a.parent)

Once upon a time there were three little sisters; and their names were
Elsie
Lacie
and
Tillie
and they lived at the bottom of a well.

print(list(enumerate(soup.a.parents)))

兄弟节点

print(list(enumerate(soup.a.next_siblings))
print(list(enumerate(soup.a.previous_siblings)))

[(0, '\n'), (1, Lacie), (2, ' \n and\n '), (3, Tillie), (4, '\n and they lived at the bottom of a well.\n ')]

[(0, '\n Once upon a time there were three little sisters; and their names were\n ')]

标准选择器

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

可根据标签名、属性、内容查找文档

name

html='''
<div class="panel">
<div class="panel-heading">
<h4>Hello</h4>
</div>
<div class="panel-body">
<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">Foo</li>
<li class="element">Bar</li>
</ul>
</div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.find_all('ul'))
print(type(soup.find_all('ul')[0]))
for ul in soup.find_all('ul'):
print(ul.find_all('li'))

attrs

print(soup.find_all(attrs={'id': 'list-1'}))
print(soup.find_all(attrs={'name': 'elements'}))
print(soup.find_all(id='list-1'))
print(soup.find_all(class_='element'))

text

print(soup.find_all(text='Foo'))

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

find返回单个元素,find_all返回所有元素

print(soup.find('ul'))
print(type(soup.find('ul')))
print(soup.find('page'))

find_parents() find_parent()

find_parents()返回所有祖先节点,find_parent()返回直接父节点。

find_next_siblings() find_next_sibling()

find_next_siblings()返回后面所有兄弟节点,find_next_sibling()返回后面第一个兄弟节点。

find_previous_siblings() find_previous_sibling()

find_previous_siblings()返回前面所有兄弟节点,find_previous_sibling()返回前面第一个兄弟节点。

find_all_next() find_next()

find_all_next()返回节点后所有符合条件的节点, find_next()返回第一个符合条件的节点

find_all_previous() 和 find_previous()

find_all_previous()返回节点后所有符合条件的节点, find_previous()返回第一个符合条件的节点

CSS选择器

通过select()直接传入CSS选择器即可完成选择

print(soup.select('.panel .panel-heading'))
print(soup.select('ul li'))
print(soup.select('#list-2 .element'))
print(type(soup.select('ul')[0])) [<div class="panel-heading">
<h4>Hello</h4>
</div>]
[<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>, <li class="element">Foo</li>, <li class="element">Bar</li>]
[<li class="element">Foo</li>, <li class="element">Bar</li>]
<class 'bs4.element.Tag'>
for ul in soup.select('ul'):
print(ul.select('li')) [<li class="element">Foo</li>, <li class="element">Bar</li>, <li class="element">Jay</li>]
[<li class="element">Foo</li>, <li class="element">Bar</li>]
for ul in soup.select('ul'):
print(ul['id'])
print(ul.attrs['id'])

list-1

list-1

list-2

list-2

获取内容

for li in soup.select('li'):
print(li.get_text())

Foo

Bar

Jay

Foo

Bar

总结

  • 推荐使用lxml解析库,必要时使用html.parser
  • 标签选择筛选功能弱但是速度快
  • 建议使用find()、find_all()查询匹配单个结果或者多个结果
  • 如果对CSS选择器熟悉建议使用select()
  • 记住使用的获取属性和文本值得方法

参考来源:https://cuiqingcai.com/5548.html

beautifulsoup的使用的更多相关文章

  1. Python爬虫小白入门(三)BeautifulSoup库

    # 一.前言 *** 上一篇演示了如何使用requests模块向网站发送http请求,获取到网页的HTML数据.这篇来演示如何使用BeautifulSoup模块来从HTML文本中提取我们想要的数据. ...

  2. 使用beautifulsoup与requests爬取数据

    1.安装需要的库 bs4 beautifulSoup  requests lxml如果使用mongodb存取数据,安装一下pymongo插件 2.常见问题 1> lxml安装问题 如果遇到lxm ...

  3. BeautifulSoup :功能使用

    # -*- coding: utf-8 -*- ''' # Author : Solomon Xie # Usage : 测试BeautifulSoup一些用法及容易出bug的地方 # Envirom ...

  4. BeautifulSoup研究一

    BeautifulSoup的文档见 https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/ 其中.contents 会将换行也记录为一个子节 ...

  5. BeautifulSoup

    参考:http://www.freebuf.com/news/special/96763.html 相关资料:http://www.jb51.net/article/65287.htm 1.Pytho ...

  6. BeautifulSoup Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER.

    BeautifulSoup很赞的东西 最近出现一个问题:Python 3.3 soup=BeautifulSoup(urllib.request.urlopen(url_path),"htm ...

  7. beautifulSoup(1)

    import re from bs4 import BeautifulSoupdoc = ['<html><head><title>Page title</t ...

  8. python BeautifulSoup模块的简要介绍

    常用介绍: pip install beautifulsoup4 # 安装模块 from bs4 import BeautifulSoup # 导入模块 soup = BeautifulSoup(ht ...

  9. BeautifulSoup 的用法

    转自:http://cuiqingcai.com/1319.html Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python ...

  10. BeautifulSoup的选择器

    用BeautifulSoup查找指定标签(元素)的时候,有几种方法: soup=BeautifulSoup(html) 1.soup.find_all(tagName),返回一个指定Tag元素的列表 ...

随机推荐

  1. CSS适配,方案

    1.尺寸常用单位:   https://www.cnblogs.com/whitewolf/p/css-em-px-percentage.html px.em.rem.% 2.CSS的长度单位适配方案 ...

  2. CF C. Fly

    题目 题目大意:第一行给出一个数n,代表有n个点,第二行给出火箭的自重,第三行给出每个点去时每吨需要的燃料,第四行给出每个点返程时每吨需要的燃料.求出发时携带的最小燃料数 分析:这题我们只要逆向思维就 ...

  3. 关于“Unknown or unsupported command 'install'”问题解决的小结

    经常需要在COMMAND命令中安装第三方库,有时会碰到“Unknown or unsupported command 'install'”这种报错. 刚开始时,以为是环境变量里面没有配置:PYTHON ...

  4. PHP中文无乱码截取

    正在上传文件反正无聊 就把php无乱码截取写出来吧` 参数说明 gbk    字符编码中,存储中文字符要2个字节 uft-8  字符编码中,存储中文字符要3个字节 0xa0  半个汉字 ord()—  ...

  5. Entity Framework 应用程序有以下优缺点

    优点: 1.跨数据库支持能力强大,只需修改配置就可以轻松实现数据库切换2.提升了开发效率,不需要在编写Sql脚本,但是有些特殊Sql脚本EF无法实现,需要我们自己编写(通过EF中的ExecuteSql ...

  6. 洛谷 P3803 【模板】多项式乘法(FFT)

    题目链接:P3803 [模板]多项式乘法(FFT) 题意 给定一个 \(n\) 次多项式 \(F(x)\) 和一个 \(m\) 次多项式 \(G(x)\),求 \(F(x)\) 和 \(G(x)\) ...

  7. PAT_A1101#Quick Sort

    Source: PAT A1101 Quick Sort (25 分) Description: There is a classical process named partition in the ...

  8. 数据挖掘Aprior算法详解及c++源码

    [算法大致描述] Aprior算法主要有两个操作,扫描数据库+统计.计算每一阶频繁项集都要扫描一次数据库并且统计出满足支持度的n阶项集. [算法主要步骤] 一.频繁一项集 算法开始第一步,通过扫描数据 ...

  9. 响应断言和json asstion

    1.要勾选Additionallly  assert value才可以输入下面的预期结果哦

  10. Excel的线程 与 SynchronizationContext的实现

    COM组件的线程模型与Excel多线程的背景知识 COM组件的线程模型被称之为Apartment模型,COM对象初始化时其执行上下文(Execution Context),他要么和单个线程关联STA( ...