BeautifulSoup 使用经验总结

文章目录

  • BeautifulSoup 使用经验总结
    • 概述
      • 安装
      • 开始使用
    • 经验总结
      • 节点对象、名称、属性
      • 节点的文本内容
      • 子节点
      • 父节点
      • 兄弟节点
      • 搜索节点
      • 使用正则表达式匹配标签名
      • 使用属性搜索
      • 使用CSS搜索
      • 使用文本内容搜索
      • 使用函数筛选

概述

处理数据,总要面对 HTML 和 XML 文档。BeautifulSoup 是一个可以从 HTML 或 XML 中提取数据的 Python 库,功能强大、使用便捷,诚为朴实有华、人见人爱的数据处理工具。

安装

自从有了 pip 这个神器,安装就不再是问题了。BeautifulSoup 支持 Python 标准库中的 HTML 解析器,也支持其他解析器。我建议使用更牛叉的第三方解析器 lxml——我曾经用它处理过单个文件几百兆字节的xml数据,反应神速,毫无迟滞感。当然,使用系统已有的解析器,除了速度和效率,基本也不会有啥问题。

$ pip install beautifulsoup4
$ pip install lxml

开始使用

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("<html>data</html>", "html.parser")  # 使用python内置标准库,速度适中,容错性好
>>> soup = BeautifulSoup("<html>data</html>", "html5lib")     # 以浏览器的方式解析文档,容错性最好
>>> soup = BeautifulSoup("<html>data</html>", ["lxml-xml"])   # lxml XML 解析器,速度快
>>> soup = BeautifulSoup("<html>data</html>", "lxml")         # lxml HTML 解析器,速度快,容错性好

如果没有指定解析器,BeautifulSoup 会自动查找使用系统可用的解析器。

经验总结

所有的例子,均以下面的html为例。

html_doc = """<html><div id="My gift"><p class="intro short-text" align="left">One</p><p class="intro short-text" align="center">Two</p><p class="intro short-text" align="right">Three</p></div><img class="photo" src="demo.jpg"><div class="photo"><a href="sdysit.com"><img src="logo.png"></a><p class="subject">山东远思信息科技有限公司</p></div></html>
"""
  • 文本也是节点,我们称之为文本型节点,比如p标签中的One,Two,Three
  • 某个节点的子节点往往比我们看到的多,因为在那些可见的子节点之外的换行、空格、制表位等,也都是某节点的文本型子节点

节点对象、名称、属性

使用lxml解析器生成一个 BeautifulSoup 对象 soup,然后可以使用标签名得到节点对象:

>>> soup = BeautifulSoup(html_doc, 'lxml')
>>> tag = soup.html
>>> tag.name
'html'
>>> tag.p.name
'p'

事实上,我们可以不用在意标签的父级是谁,直接从soup得到节点对象:

>>> soup.p.name
'p'
>>> soup.img['src']
'demo.jpg'
>>> soup.img.attrs
{'class': ['photo'], 'src': 'demo.jpg'}
>>> soup.p['class']
['intro', 'short-text']
>>> soup.div['id']
'My gift'

很显然,这样的方式得到的节点,一定是html中第一个同类型的标签。上面的例子还演示了如何取得节点对象的所有的属性和指定属性。当class属性有多个值时,返回的是一个列表,而id属性不承认多值。

节点的文本内容

取得一个节点的文本内容,有很多种方法,比如:

>>> soup.p.text
'One'
>>> soup.p.getText()
'One'
>>> soup.p.get_text()
'One'
>>> soup.p.string
'One'
>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>

当一个节点只有文本型子节点的时候,前三种方法的效果是完全一致的,第四种方法看上去差不多,但返回的类型是NavigableString(可遍历的字符串)。

当节点包括元素型子节点的时候,输出的结果可能已经不是我们需要的了。此时,可以使用 .strings 或者 .stripped_strings(去掉空行和多余的空格) 得到一个迭代器,遍历即可得到我们想要的内容。

>>> soup.div.text
'\nOne\nTwo\nThree\n'
>>> soup.html.text
'\n\nOne\nTwo\nThree\n\n\n\n\n山东远思信息科技有限公司\n\n'
>>> for item in soup.div.stripped_strings:print(item)One
Two
Three

子节点

.contents, .children,.descendants 都可以取得节点的子节点,但用法各不相同:

  • .contents, .children 只能取得直接子节点,.descendants 则可以递归取得所有子节点
  • .contents 返回的子节点的列表,.children,.descendants 返回的是迭代器

父节点

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

>>> soup.p.parent.name
'div'

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

>>> for parent in soup.p.parents:print(parent.name)div
body
html
[document]

兄弟节点

可以使用 .next_sibling 和 .previous_sibling 属性来查询前一个或后一个兄弟节点,但必须注意,除了可见的兄弟节点,还可能存在换行、空格、制表位等文本型的兄弟节点混杂其中。

可以使用 .next_siblings 和 .previous_siblings 属性取得当前节点的前面或后面的兄弟节点的迭代输出。

搜索节点

一般使用 find() 和 find_all() 搜索符合条件的第一个节点和全部节点的列表。

>>> soup.find('p')
<p align="left" class="intro short-text">One</p>
>>> soup.find_all('img')
[<img class="photo" src="demo.jpg"/>, <img src="logo.png"/>]

使用正则表达式匹配标签名

搜索以d开头的标签:

>>> import re
>>> for tag in soup.find_all(re.compile("^d")):print(tag.name)div
div

使用属性搜索

>>> soup.find_all(id='My gift')[0].name # 查找id=My gift的节点
'div'
>>> soup.find_all(id=True)[0].name # 查找有id属性的节点
'div'
>>> soup.find_all(attrs={"id":"My gift"})[0].name # 使用attrs查找
'div'
>>> soup.find_all(attrs={"class":"intro short-text","align":"right"})[0].text # 使用attrs查找
'Three'
>>> soup.find_all(attrs={"align":"right"})[0].text # 使用attrs查找
'Three'

使用CSS搜索

>>> soup.find_all("p", class_="intro")
[<p align="left" class="intro short-text">One</p>, <p align="center" class="intro short-text">Two</p>, <p align="right" class="intro short-text">Three</p>]
>>> soup.find_all("p", class_="intro short-text")
[<p align="left" class="intro short-text">One</p>, <p align="center" class="intro short-text">Two</p>, <p align="right" class="intro short-text">Three</p>]
>>>

使用文本内容搜索

>>> soup.find_all(string="Two")
['Two']
>>> soup.find_all(string=re.compile("Th"))
['Three']

使用函数筛选

>>> def justdoit(tag):return tag.parent.has_attr('id') and tag['align']=='center'>>> soup.find_all(justdoit)
[<p align="center" class="intro short-text">Two</p>]

BeautifulSoup 使用经验总结相关推荐

  1. 【转载】Session服务器配置指南与使用经验

    作者:张子秋 出处:http://www.cnblogs.com/zhangziqiu/ 原文链接:http://www.cnblogs.com/zhangziqiu/archive/2009/03/ ...

  2. python beautifulsoup模拟点击_Python爬虫丨BeautifulSoup实践

    项目分析 爬取的网站是下厨房,目标是固定栏目[本周最受欢迎] 可以看到我们要爬取的/explore/不在禁止爬取的列表内 1.先看下页面 计划拿到的信息是:菜名.所需材料.和菜名所对应的详情页URL ...

  3. python html解析查找字符串_用python的BeautifulSoup分析html

    序言 之前用python爬取网页的时候,一直用的是regex或者自带的库sgmllib里的SGMLParser.但是遇到复杂一点的情况时,SGMLParser往往就不那么给力了!(哈,难道说我 too ...

  4. Windows下Python 3.6 安装BeautifulSoup库

    " 介绍Python库BeautifulSoup安装." 01 - BeautifulSoup库介绍 Beautiful Soup是Python的一个库,支持Python 2和Py ...

  5. 单相计量芯片RN8209D使用经验分享(转)

    单相计量芯片RN8209D使用经验分享 转载于:https://www.cnblogs.com/LittleTiger/p/10736060.html

  6. beautifulsoup以及正则表达式re之间的一些知识!

    代码: import requests import re from bs4 import BeautifulSoup r = requests.get("https://python123 ...

  7. beautifulsoup里面的find()和findall()小代码测试

    区别: 大白话说,就是find()可以应对于单个.然而find_all()却要一次查找好多! 代码: import requests from bs4 import BeautifulSoup r = ...

  8. beautifulsoup关于标签的初学习

    代码: import requests from bs4 import BeautifulSoup r = requests.get("https://python123.io/ws/dem ...

  9. BeautifulSoup的初使用!

    简单使用: python小例子链接: https://python123.io/ws/demo.html 代码: import requests from bs4 import BeautifulSo ...

  10. python功能性爬虫案例_Python使用requests及BeautifulSoup构建爬虫实例代码

    本文研究的主要是Python使用requests及BeautifulSoup构建一个网络爬虫,具体步骤如下. 功能说明 在Python下面可使用requests模块请求某个url获取响应的html文件 ...

最新文章

  1. CNNIC报告:我国网民达7.72亿 人工智能取得重要进展
  2. 一个可以检测网络内主机类型的脚本
  3. MySQL(6)数据库中的高级(进阶) SQL 语句
  4. 斐波那契查找+思路分析
  5. 牛客14342 神奇的数字
  6. 安卓项目打开有时候manifests不见了_手机通话音量太小?教你打开这个开关,再也不怕听不清了...
  7. 用dl元素编辑html个人信息,html dl dt dd标签元素语法结构与使用
  8. 2021辽宁高考成绩查询公布,2021辽宁高考成绩什么时候出
  9. vs2005配置c语言连接mysql
  10. 软件测试的几大误区(带你踩坑)
  11. 《C#高级编程(第六版)》泛型学习笔记(一):泛型优点和特性 (转载)
  12. 给Eclipse设置android的SDK位置时,出现这个:This Android SDK requires Andr...ate ADT to the latest
  13. SEM常用的数据统计工具之百度统计
  14. 值得收藏的网站----安全
  15. U盘PE启动盘制作好后,如何进入PE系统?
  16. python keys方法_Robot Framework selenium操作键盘press keys方法详解(Python篇)
  17. 虚幻4皮肤材质_虚幻引擎4.5版本预览说明
  18. 百度AI身份证识别接口,iOS上传base64图片报错216201问题解决办法总结
  19. CAJ文件不存在或者不能正常访问问题解决
  20. 浏览器下载文件不全解决方法

热门文章

  1. C2 - Skyscrapers (hard version),Codeforces Round #622 (Div. 2),单调栈
  2. 数据结构-BF算法和KMP算法
  3. UTC时间转化为北京时间
  4. Jaspersoft Studio 报表模板设计
  5. python:打飞机游戏
  6. LA 5846 霓虹灯广告牌(单色三角形问题)
  7. 常州2021高考成绩查询,2021年常州高考各高中成绩及本科升学率数据排名及分析...
  8. 计划的主体部分应有哪些内容_计划练习题
  9. 拆与组装计算机的全过程,拆装及组装电脑方法
  10. 头条小程序可以使用uniapp的地图选择(uni.chooseLocation)