BeautifulSoup使用

主要内容

  • BeautifulSoup 在解析XML中常用的方法
  • 处理XML使用过程中技巧总结

主要参考

Beautiful Soup 4.2.0 文档

常用方法

初始方法
BeautifulSoup("

", "lxml") #
BeautifulSoup("

", "html5lib") #

通过Beautiful Soup输出文档时,不管输入文档是什么编码方式,输出编码均为UTF-8编码。
值得注意的是,如果是XML文件解析,需要用open('file.xml').read()读取为字符串后,使用BeautifulSoup(source_string, 'xml')解析。

子节点

可以通过tag的name直接获取(此方法的缺点是,Tag.name中含有‘-’等符号时会对Python语法造成干扰)

soup.head
# The Dormouse's story

soup.title
# The Dormouse's story

通过find() | find_all() 查找子节点,使用 find_all 方法并设置 limit=1 参数不如直接使用 find() 方法.下面两行代码是等价的:

soup.find_all('title', limit=1)
# [The Dormouse's story]

soup.find('title')
# The Dormouse's story

解析HTML,查找指定Class属性时注意: soup.find('div', _class='highlight')

  • find返回可以为None,所以避免出现以下错误:
soup.find('p').text
>>AttributeError: 'NoneType' object has no attribute 'text'
# 
t = soup.find('p')
if t:
    t.text
.strings 和 stripped_strings
  • 如果tag中包含多个字符串 ,可以使用.strings来循环获取:
for string in soup.strings:
    print(repr(string))
    # u"The Dormouse's story"
    # u'\n\n'
    # u"The Dormouse's story"
    # u'\n\n'
  • 输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容:
for string in soup.stripped_strings:
    print(repr(string))
    # u"The Dormouse's story"
    # u"The Dormouse's story"

你可能感兴趣的:(BeautifulSoup使用)