导入并将 html 转成 unicode
from bs4 import BeautifulSoup soup = BeautifulSoup(open("index.html")) soup = BeautifulSoup("<html>data</html>")如果只想得到tag中包含的文本内容,可以使用get_text()
Tag 是什么?通俗点讲就是 HTML 中的一个个标签,以豆瓣电影排行榜某段html 为例:
<a href="https://movie.douban.com/subject/1292052/" class=""> <span class="title">肖申克的救赎</span> <span class="title"> / The Shawshank Redemption</span> <span class="other"> / 月黑高飞(港) / 刺激1995(台)</span> <span class="playable">[可播放]</span> </a> tag: a和 spanattrs(属性):class=“title"、class=“other"和href="https://movie.douban.com/subject/1292052/"等等Tag.a 标签即代表了所有的信息
print(soup.a) # <a class="" href="https://movie.douban.com/subject/1292052/"> <span class="title">肖申克的救赎</span> <span class="title"> / The Shawshank Redemption</span> <span class="other"> / 月黑高飞(港) / 刺激1995(台)</span> <span class="playable">[可播放]</span> </a>已经得到了标签的内容,那么问题来了,我们要想获取标签内部的文字怎么办呢?很简单,用 .string 即可,例如:
print(soup.a.string) # 肖申克的救赎BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下
print(type(soup.a)) # <class 'bs4.element.Tag'> print(soup.name) #[document] print(soup.attrs ) #{}Tag , NavigableString , BeautifulSoup 几乎覆盖了html和xml中的所有内容,但是还有一些特殊对象.容易让人担心的内容是文档的注释部分:
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>" soup = BeautifulSoup(markup) comment = soup.b.string type(comment) # <class 'bs4.element.Comment'>可以comment 对象会使用特殊的格式输出:
print(soup.b.prettify()) # <b> # <!--Hey, buddy. Want to buy a used parser?--> # </b>首先了解下DOM树:
find_all() 方法唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果
find( name , attrs , recursive , text , **kwargs )参数解析:
name:所有名字为 name 的tagattrs:属性Recursive:Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数