小白学爬虫笔记6---标签树的遍历

遍历方法

标签树的下行遍历

  • .contents 子节点的列表
  • .children 子节点的迭代类型
  • .descendants 子孙节点的迭代类型

 

samples:

soup = BeautifulSoup(demo, "html.parser")
soup.head
soup.head.contents
soup.body.contents
len(soup.body.contents)
soup.body.contents[1]
for child in soup.body.children:
    do sth

标签树的上行遍历

  • .parent
  • .parents

 

samples:

soup = BeautifulSoup(demo,"html.parser")
soup.title.parent
soup.html.parent # html的父级就是它自己

soup = BeautifulSoup(demo,"html.parser")
for parent in soup.a.parents:
    if parent is null:

    else:
        do sth

标签树的平行遍历

  • .next_sibling
  • .previous_sibling
  • .next_siblings #所有
  • .previous.siblings

 

平行遍历必须发生在同一父节点下 samples:

soup = BeautifulSoup(demo,"html.parser")
soup.a.next_sibling # ' and '   可能存在NavigableString类型
soup.a.next_sibling.next_sibling
soup.a.previous_sibling

猜你喜欢

转载自blog.csdn.net/paleyellow/article/details/81096171