继上一篇BeautifulSoup的高级应用,主要解说的是contents children descendants string strings stripped_strings。本篇主要解说.parent .parents .next_sibling .previous_sibling .next_siblings .previous_siblings

本篇博客继续使用上篇的html页面内容:

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

继续分析文档树 ,每一个 tag或字符串都有父节点 :被包括在某个 tag中

.parent:

通过 .parent 属性来获取某个元素的父节点.在样例html文档中,标签是标签的父节点:

title_tag = soup.title
title_tag
# <title>The Dormouse's story</title>
title_tag.parent
# <head><title>The Dormouse's story</title></head>

文档title的字符串也有父节点:标签

title_tag.string.parent
# <title>The Dormouse's story</title>

文档的顶层节点比方的父节点是 BeautifulSoup 对象:

html_tag = soup.html
type(html_tag.parent)
# <class 'bs4.BeautifulSoup'>

BeautifulSoup 对象的 .parent 是None。

.parents

通过元素的.parents属性能够递归得到元素的全部父辈节点 , 以下的样例使用了 .parents方 法遍历了 标签到根节点 的全部节点:

link = soup.a
link
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
for parent in link.parents:
if parent is None:
print(parent)
else:
print(parent.name)
# p
# body
# html
# [document]
# None

兄弟节点

举例说明:

<a>
<b>text1</b>
<c>text2</c>
</a>

这里的b和c节点为兄弟节点

.next_sibling 和 .previous_sibling .:

在文档树中 ,使用 .next_sibling 和 .previous_sibling 属性来查询兄弟节点:

sibling_soup = BeautifulSoup("<a><b>text1</b><c>text2</c></b></a>")
sibling_soup.b.next_sibling
# <c>text2</c>
sibling_soup.c.previous_sibling
# <b>text1</b>

b 标签有.next_sibling 属性 ,可是没有 .previous_sibling 属性 ,由于 b标签在同级节点中是第一个 .同理 ,c标签有 .previous_sibling 属性 ,却没有 .next_sibling 属性 。

link = soup.a link
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
link.next_sibling
# u',\n'

注意:第一个a标签的next_sibling 属性值为 。\n

link.next_sibling.next_sibling
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>

第一个a标签的next_sibling的next_sibling 属性值为Lacie

.next_siblings.previous_siblings.

通过 .next_siblings 和 .previous_siblings 属性对当前节点的兄弟节点迭代输出:

for sibling in soup.a.next_siblings:
print(repr(sibling)) # u',\n'
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
# u' and\n'
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
# u'; and they lived at the bottom of a well.'
# None
for sibling in soup.find(id="link3").previous_siblings: print(repr(sibling))
# ' and\n'
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
# u',\n'
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
# u'Once upon a time there were three little sisters; and their names were\n'
# None

回退和前进:

举例html例如以下:

<html><head><title>The Dormouse's story</title></head> <p class="title"><b>The Dormouse's story</b></p>

HTML 解析器把这段字符串转换成一连的事件 : “ 打开标签 ”加入一段字符串 ”,关闭 标签 ”,”打开

标签 ”, 等.Beautiful Soup提供了重现解析器初始化过程的方法

.next_element 和 .previous_element .

.next_element 属性指向解析过程中下一个被的对象 (字符串或 tag),结果可能 与 .next_sibling 同样 ,但一般是不一样的 .

last_a_tag = soup.find("a", id="link3")
last_a_tag
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
last_a_tag.next_sibling
# '; and they lived at the bottom of a well.'

但这个 标签的 .next_element 属性结果是在标签被解析之后的内容 ,不是标 签后的句子部分 ,应该是字符串 ”Tillie”:

last_a_tag.next_element
# u'Tillie'

.previous_element 属性刚好与.next_element 相反 ,它指向当前被解 析的对象的前一个解析对象 :

last_a_tag.previous_element
# u' and\n'
last_a_tag.previous_element.next_element
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

.next_elements 和 .previous_elements

通过 .next_elements 和 .previous_elements 的迭代器就能够向前或后訪问文档解析内容 ,就好像文档正在被解析一样 :

for element in last_a_tag.next_elements:                  print(repr(element))
# u'Tillie'
# u';\nand they lived at the bottom of a well.'
# u'\n\n'
# <p class="story">...</p>
# u'...'
# u'\n'
# None

下一篇 将解说一下BeautifulSoup的搜索文档树的高级方法。

BeautifulSoup的高级应用 之.parent .parents .next_sibling.previous_sibling.next_siblings.previous_siblings的更多相关文章

  1. jQuery查找——parent/parents/parentsUntil/closest

    jquery的parent(),parents(),parentsUntil(),closest()都是向上查找父级元素,具体用法不同 parent():取得一个包含着所有匹配元素的唯一父元素的元素集 ...

  2. BeautifulSoup的高级应用 之 contents children descendants string strings stripped_strings

    继上一节.BeautifulSoup的高级应用 之 find findAll,这一节,主要解说BeautifulSoup有关的其它几个重要应用函数. 本篇中,所使用的html为: html_doc = ...

  3. jQuery 利用 parent() parents() 寻找父级 或祖宗元素

    $(this).parent().parent().parent().parent().parent().remove(); //此方法通过parent()一级一级往上找   $(this).pare ...

  4. jquery parent() parents() closest()区别

    分类: 前端开发 parent是找当前元素的第一个父节点,不管匹不匹配都不继续往下找 parents是找当前元素的所有父节点  closest() 是找当前元素的所有父节点 ,直到找到第一个匹配的父节 ...

  5. parent,parents和closest

    1.parent parent() 获得当前匹配元素集合中每个元素的父元素,使用选择器进行筛选是可选的. <ul id="menu" style="width:10 ...

  6. [转载]JQuery.closest(),parent(),parents()寻找父节点

    1.通过item-1查找 level-3(查找直接上级) $('li.item-1').closest('ul') $('li.item-1').parent() $('li.item-1').par ...

  7. jquery 常用选择器 回顾 ajax() parent() parents() children() siblings() find() eq() has() filter() next()

    1. $.ajax() ajax 本身是异步操作,当需要将 异步 改为 同步时: async: false 2.parent()  父级元素  和  parents() 祖先元素 的区别 parent ...

  8. parent() parents() parentsUntil()三者之间的对比

    $(document).ready(function(){ $("span").parent(); });只拿到span的父级标签 $(document).ready(functi ...

  9. 初识Python和使用Python爬虫

     一.python基础知识了解:   1.特点: Python的语言特性: Python是一门具有强类型(即变量类型是强制要求的).动态性.隐式类型(不需要做变量声明).大小写敏感(var和VAR代表 ...

随机推荐

  1. ItChat与图灵机器人的结合

    前景: 我在知乎关注一位大佬 名字叫 LittleCoder 我是在他开发ItChat包时关注的 ItChat已经完成了微信的个人账号的API接口 已经实现了实时获取用户的即时信息并自动化进行回应 后 ...

  2. 2019-03-20 Python爬取需要登录的有验证码的网站

    当你向验证码发起请求的时候,就有session了,记录下这次session 因为每当你请求一次验证码 或者 请求一次登录首页,验证码都在变动 验证码的链接可能不是固定的,可能需要GET/POST请求, ...

  3. css预编译器——Less的使用

      方法一:仅介绍在客户端环境下使用的方法 1 新建test.less并引入.less该文件(和css一样在head处引入),注意rel="stylesheet/less": &l ...

  4. pip安装-mac电脑

    If you meant "pip" specifically: Homebrew provides pip via: `brew install python`. However ...

  5. POJ 3695

    可以用容斥原理来求.求两个矩形的并的时候可以使用条件 x1=max(p.x1,q.x1);y1=max(p.y1,q.y1);x2=min(p.x2,q.x2);y2=min(p.y2,q.y2); ...

  6. 关于Segmentation fault错误

    今天敲代码时候出现了Segmentation fault,在网上查了一些资料,基本上的原因是.非法的内存訪问. 比如数组的越界,在循环操作时循环变量的控制问题,也有字符串拷贝时长度溢出,指针指向了非法 ...

  7. poj2965 The Pilots Brothers&#39; refrigerator(直接计算或枚举Enum+dfs)

    转载请注明出处:http://blog.csdn.net/u012860063? viewmode=contents 题目链接:http://poj.org/problem? id=2965 ---- ...

  8. PyQt: LineEdit的智能输入提示

    使用的的类是QtGui.QCompleter from PyQt4 import QtGui,QtCore str = QtCore.QStringList(['a','air','airbus']) ...

  9. 浅谈关于collection接口及相关容器类(一)

    Collection在英文单词的意思是:採集,收集. 而在JAVA API 文档中它是一个收集数据对象的容器. Collection作为容器类的根接口.例如以下图(部分子接口未写出): waterma ...

  10. c语言运算符优先级与while循环案例

    sizeof可以获取数据类型的内存中的大小(字节) #include <stdio.h> #include <stdlib.h> // standared 标准 // inpu ...