BeautifulSoup使用

主要内容

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

主要参考

Beautiful Soup 4.2.0 文档

常用方法

初始方法
BeautifulSoup("<a></p>", "lxml")
# <html><body><a></a></body></html>
BeautifulSoup("<a></p>", "html5lib")
# <html><head></head><body><a><p></p></a></body></html>

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

子节点

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

soup.head
# <head><title>The Dormouse's story</title></head>

soup.title
# <title>The Dormouse's story</title>

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

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

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

解析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"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容