python - bs4 .children打印出来的结果为什么是这样?
怪我咯
怪我咯 2017-04-18 09:45:06
[Python讨论组]

最近在练习写爬虫,在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)

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

<tr><th>
Item Title
</th><th>
Description
</th><th>
Cost
</th><th>
Image
</th></tr>
<th>
Item Title
</th>

Item Title

<th>
Description
</th>

Description

<th>
Cost
</th>

Cost

<th>
Image
</th>

Image

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

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
PHP中文网

文档不是说得挺清楚了吗,多看几次文档就理解
链接描述

PHPz

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

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

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

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

<title>The Dormouse's story</title>
The Dormouse's story
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号