soup.find_all('a')
# [<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>]
子节点:在分析HTML过程中通常需要分析tag的子节点,而tag的 .contents 属性可以将tag的子节点以列表的方式输出。字符串没有.contents属性,因为字符串没有子节点。
head_tag = soup.head
head_tag
# <head><title>The Dormouse's story</title></head>
head_tag.contents
[<title>The Dormouse's story</title>]
title_tag = head_tag.contents[0]
title_tag
# <title>The Dormouse's story</title>
title_tag.contents
# [u'The Dormouse's story']
通过tag的 .children ,可以对tag的子节点进行循环:
for child in title_tag.children:
print(child)
# The Dormouse's story
子孙节点:同样.descendants 属性可以对所有tag的子孙节点进行递归循环:
for child in head_tag.descendants:
print(child)
# <title>The Dormouse's story</title>
# The Dormouse's story
父节点:通过 .parent 属性来获取某个元素的父节点.在例子“爱丽丝”的文档中,
标签是标签的父节点,换句话就是增加一层标签。
注意:文档的顶层节点比如的父节点是 BeautifulSoup 对象,BeautifulSoup 对象的 .parent 是None。
title_tag = soup.title
title_tag
# <title>The Dormouse's story</title>
title_tag.parent
# <head><title>The Dormouse's story</title></head>
title_tag.string.parent
# <title>The Dormouse's story</title>
兄弟节点:因为标签和标签是同一层:他们是同一个元素的子节点,所以和可以被称为兄弟节点。一段文档以标准格式输出时,兄弟节点有相同的缩进级别.在代码中也可以使用这种关系。
sibling_soup = BeautifulSoup("<a><b>text1</b><c>text2</c></b></a>")
print(sibling_soup.prettify())
# <html>
# <body>
# <a>
# <b>
# text1
# </b>
# <c>
# text2
# </c>
# </a>
# </body>
# </html>
在文档树中,使用 .next_sibling 和 .previous_sibling 属性来查询兄弟节点。标签有.next_sibling 属性,但是没有.previous_sibling 属性,因为标签在同级节点中是第一个。同理标签有.previous_sibling 属性,却没有.next_sibling 属性:
sibling_soup.b.next_sibling
# <c>text2</c>
sibling_soup.c.previous_sibling
# <b>text1</b>
(By:Eastmount 2015-3-25 下午6点 )**
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-33240-6.html
必须驱赶
很棒