python 理解Beautiful Soup库的基本元素

理解Beautiful Soup的基本元素是理解Beautiful Soup库的基础。

首先我们说明一下Beautiful Soup库能干什么。

我们以打开html文件为例。

任何一组html文件它都是以尖括号为组的标签组织起来的。而这些标签建立起来的东西我们称之为标签树。

而Beautiful Soup库是解析,遍历,维护标签树的功能库。

标签的具体格式如图:

Beautiful Soup库常见的四种解析器:

现在我们来介绍一下Beautiful Soup库的基本元素:

下面我们来介绍一下获得tag标签的相关方法

任何语法标签都可以用soup.tag方法访问获得,比如我们要获取某个界面的a标签:

import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import  BeautifulSoup
soup = BeautifulSoup(demo, "html.parser")
tag = soup.a
print(tag)

输出为:

<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>

但是当存在多个标签的时候,我们用soup.tag只能返回其中第一个。

name表示获取相关标签的名字,比如:

import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import  BeautifulSoup
soup = BeautifulSoup(demo, "html.parser")
print(soup.a.parent.name)
print(soup.a.parent.parent.name)

输出为:

p
body

标签的属性Attributes是在标签中表明标签特点的相关区域。

举个例子:

import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import  BeautifulSoup
soup = BeautifulSoup(demo, "html.parser")
tag = soup.a
print(tag.attrs)

输出:

{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}

我们再来看一下comment类型。

在html5界面中 我们用<!--abc-->表示注释abc,而comment标签可以表示字符串中被注释的部分。

如:

from bs4 import BeautifulSoup
newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is"
                        "not a comment</p>","html.parser")
print(type(newsoup.b.string))
print(type(newsoup.p.string))

输出:

<class 'bs4.element.Comment'>
<class 'bs4.element.NavigableString'>

不过这个comment在bs4里面并不常用。

猜你喜欢

转载自blog.csdn.net/k_koris/article/details/83017250