python - bs4 .children打印出来的结果为什么是这样?

 手机用户2602891751 发布于 2022-10-27 09:37

最近在练习写爬虫,在WebScrapingwithPython一书第20页中的一个例子:

from urllib.request import urlopen

from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")

bsObj = BeautifulSoup(html)

for child in bsObj.find("table",{"id":"giftList"}).children:
    print(child)

我把.children换成.descendants:

for child in bsObj.find('table',{'id':'giftList'}).descendants:
    print(child)

打印出来的结果为什么会有这些重复信息,比如这个:


Item Title

Description

Cost

Image


Item Title


Item Title


Description


Description


Cost


Cost


Image


Image

问题:
1.为什么Item Title,Description,Cost,Image这些字出现了两次呢?
2.通过这个例子还是不太明白children和descendants的区别T.T哪位高人点拨下,谢谢

2 个回答
  • descendants函数的行为是遍历某个标签的子元素,同时继续递归遍历该子元素。

    举个栗子:
    head标签的子标签title为:

    <title>The Dormouse's story</title>

    则使用descendants遍历时的输出为:

    <title>The Dormouse's story</title>
    The Dormouse's story
    2022-10-27 09:37 回答
  • 文档不是说得挺清楚了吗,多看几次文档就理解
    链接描述

    2022-10-27 09:37 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有