Beautiful Soup 节点选择器
1.选择元素
html = '''
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml') # 解析文本成lxml解释器
print(soup.title) # <title>The Dormouse's story</title>
print(type(soup.title)) # <class 'bs4.element.Tag'> 经过选择器选择后,选择结果都是Tag类型
print(soup.title.string) # The Dormouse's story 调用string属性可以得到节点的文本内容
print(soup.head) # <head><title>The Dormouse's story</title></head> 选择head节点,结果也是节点加其内容
print(soup.p) # <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
'''
最后选择了p节点,我们发现结果是第一个p节点的内容,后面的几个p节点并没有被选到,也就是说,当有多个节点时,这种
选择方式只会选择到第一个匹配的节点,其它的后面节点都会被忽略
'''
2. 嵌套选择
'''
在之前操作中,我们知道了每一个返回结果都是bs4.element.Tag类型,它同样可以继续调用节点进行下一步的选择,比如,我们获取了head节点元素,
我们可以继续调用head来选取其内部的head节点元素
'''
html = '''
<html><head><title>The Dormouse's story</title></head>
<body>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.head.title) # 调用head之后再次调用title节点元素
print(type(soup.head.title))
'''打印它的类型可以看到是bs4.element.Tag类型,也就是说在Tag类型的基础上再次选择得到的依然是Tag类型,每次返回的结果都相同,
所以这样就可以嵌套选择了
'''
print(soup.head.string) # 输出它的string属性,也就是节点例的文本内容