BeautifulSoup的find()和find_all()

发布时间:2022-07-02 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了BeautifulSoup的find()和find_all()脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

BeautifulSoup里的find()0和find_all()可能是你最常用的两个函数。借助她们,你可以通过标签的不同属性轻松地过滤HTML页面,查找需要的标签组或者单个标签。

find_all(tag, attributes, recursive, text, limIT, keywords)

find_all(标签、属性、递归、文本、限制、关键词)

find(tag, attributes, recursive, text, keywords)

95%的时间里都只需要使用前2个参数:tag和attributes,即标签和属性

参数attributes用一个python字典封装一个标签的若干属性和对应的属性值。例如,下面的函数会返回HTML文档中绿色的span标签

.find_all('span',{'class':'green'}

 

网页链接:http://www.pythonscraping.COM/pages/warandPEace.html

BeautifulSoup的find()和find_all()

 

 

 通过BeautifulSoup对象,我们可以用find_all函数提取只包含在<span class="green">...</span>标签里的文字,这样就会得到一个人物名称的python列表。

From urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
bs = BeautifulSoup(html.read(),'html.parser')

nameList = bs.find_all('span',{'class':'green'})

for name in nameList:
    PRint(name.get_text())

 

脚本宝典总结

以上是脚本宝典为你收集整理的BeautifulSoup的find()和find_all()全部内容,希望文章能够帮你解决BeautifulSoup的find()和find_all()所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。