正文
Beautiful Soup 4.2.0 doc_tag、Name、Attributes、多值属性
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
找到了bs4的中文文档,对昨天爬虫程序里所涉及的bs4库进行学习。这篇代码涉及到tag、Name、Attributes以及多值属性。
'''
对象的种类
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象。
所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment 。
''' from bs4 import BeautifulSoup soup = BeautifulSoup('<b class="boldest">Extremely bold</b>','lxml')
tag = soup.b
type(tag)
#<class 'bs4.element.Tag'> #TAG.NAME
tag
#<b class="boldest">Extremely bold</b>
tag.name
#'b'
tag.name = 'blockquote'
tag
#<blockquote class="boldest">Extremely bold</blockquote>
'''
即tag首的'<'后和tag尾'</>'内,就是这个tag的名称.
如果改变了tag的name,那将影响所有通过当前Beautiful Soup对象生成的HTML文档
'''
tag.name = 'b' #Attributes
'''一个tag可以有多个属性。如tag <b class="boldest">,他有一个"class"属性,值为"boldest"。'''
#tag属性的操作方法与字典相同。
tag['class']
# u'boldest'
tag.attrs #“点”取属性
# {u'class':u'boldest'}
'''
tag的属性可以被添加、删除或修改。tag的属性操作方法与字典一样。
'''
tag['class'] = 'verybold' #属性查看
tag['id'] = 1 #属性查看
tag
# <blockquote class="verybold" id="1">Extremely bold</blockquote> del tag['class'] #属性删除
del tag['id'] #属性删除
tag
# <blockquote>Extremely bold</blockquote> tag['class'] #删除属性后查看,报错
# KeyError: 'class'
print(tag.get('class'))
# None #多值属性
'''
最常见的多值属性是class,还有一些多值属性如 rel, rev, accept-charset, headers,accesskey等。
多值属性在 BeautifulSoup 中的返回类型是list:
'''
css_soup = BeautifulSoup('<p class="body strikeout"></p>') #这里虽然body和strikeout只用了一个空格隔开,但其仍然会被隔开返回。(大概因为在HTML的语法里这就代表了两个属性)
css_soup.p['class']
# ["body", "skrikeout"] css_soup = BeautifulSoup('<p class="body"></p>')
css_soup.p['class']
# ["body"] #这里虽然class的属性只有一个值,但是因为class本身是一个多值属性,故返回了list
'''
(接上一行注释)而如果某个属性看上去有多个值,但在任何版本的HTML定义中都没有被定义为多值属性,
那么BeautifulSoup会将这个属性作为字符串返回。如下↓
'''
id_soup = Beautiful('<p id="my id"></p>')
id_soup.p['id']
# 'my id'
'''
将tag转换为字符串时,多值属性会合并为一个值
'''
rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>')
rel_soup.a['rel']
# ['index']
rel_soup.a['rel'] = ['index','contents']#给a标签的rel属性添加值,转化在html里就是空格连接
print(rel_soup.p)
# <p>Back to the <a rel="index contents">homepage</a></p>
'''
如果转换的文档是XML格式,那么tag中不包含多值属性
'''
xml_soup = BrautifulSoup('<p class="body strikeout"></p>','xml')#lxml有多值属性,xml没有
xml_soup.p['class'] #xml里的class属性值输出出来仍然是(如非多值属性的)字符串形式,而非列表
# u'body strikeout' #可以遍历的字符串
'''
字符串常被包含在tag内,BeautifulSoup用 NavigableString 类来包装tag中的字符串:
'''
tag.string
# u'Extremely bold'
type(tag.string)
# <class 'bs4.element.NavigableString'>
'''
一个 NavigableString 字符串与Python中的Unicode字符串相同,
并且还支持包含在遍历文档树和搜索文档树中的一些特性,
通过unicode()方法可以直接将 NavigableString 对象转换成 Unicode 字符串:
'''
unicode_string = unicode(tag.string)
unicode_string
# u'Extremely bold'
type(unicode_string)
# <type 'unicode'>
'''
tag中包含的字符串不能编辑,但是可以被替换成其它的字符串,用replace_with()方法:
'''