find 和 find_all 用法

soup = BeautifulSoup(requests.get(url).text, 'html.parser')

soup.find('span', class_='item_hot_topic_title')     这个是只能找到第一个span标签 样式为 class='item_hot_topic_title',就算后面还有匹配的也不去获取

span.find_all('span', class_='item_hot_topic_title')  这个就能找到页面上所有span标签 样式为 class='item_hot_topic_title'

soup.find_all(["a", "b"])   找到所有a和b的标签已数组形式返回,传参为 True 返回页面所有标签已数组形式

其他用法:

soup.find_all("title")
# [<title>The Dormouse's story</title>]

soup.find_all("p", "title")
# [<p class="title"><b>The Dormouse's story</b></p>]

soup.find_all("a")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.find_all(id="link2")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

import re
soup.find(text=re.compile("sisters"))
# u'Once upon a time there were three little sisters; and their names were
'

其他方法见官网真的很多https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id85
原文地址:https://www.cnblogs.com/kaibindirver/p/9929732.html