我们将通过下面的举例来说明两个函数的区别

首先打开一个网页https://blog.csdn.net/xiaohukun/article/details/77679134

这是一篇博客,审查元素,选取如下图元素

BeautifulSoup中children函数和desscendants函数的区别

使用children函数,代码为

from urllib import request
from bs4 import BeautifulSoup

if __name__ == '__main__':
    url = 'https://blog.csdn.net/xiaohukun/article/details/77679134'
    html = request.urlopen(url)
    bsobj = BeautifulSoup(html)

    for child in bsobj.find('div',{'class':'article-info-box'}).children:

        print(child)

输出为:

BeautifulSoup中children函数和desscendants函数的区别

使用descendants函数,代码为

from urllib import request
from bs4 import BeautifulSoup

if __name__ == '__main__':
    url = 'https://blog.csdn.net/xiaohukun/article/details/77679134'
    html = request.urlopen(url)
    bsobj = BeautifulSoup(html)

    for child in bsobj.find('div',{'class':'article-info-box'}).descendants:

        print(child)

输出为:

BeautifulSoup中children函数和desscendants函数的区别

通过观察两个函数的输出结果,children函数输出所有的子标签和后代标签,descendants函数在children函数输出的基础上把后代标签循环输出。

相关文章:

  • 2021-07-19
  • 2021-07-25
  • 2021-06-02
  • 2021-12-19
  • 2021-10-23
  • 2021-06-18
  • 2022-12-23
  • 2021-09-23
猜你喜欢
  • 2021-11-05
  • 2021-09-03
  • 2022-12-23
  • 2022-12-23
  • 2021-10-17
  • 2022-12-23
  • 2021-07-03
相关资源
相似解决方案