不用正则也可匹配html语言,代替正则解析html的这个工具叫做Beautiful Soup(美味的汤?哈哈哈哈哈哈哈)
安装Beautiful Soup
Pip install Beautiful bs4
Beautiful Soup的功能-格式化处理
处理html字符串,用lxml解析html(lxml为第三方库,需要安装pip install lxml)
解析如下的格式
html_doc=""""
The Dormouse story
The Dormouse story
Once upon a time there are three little sisters;and their names were
Lacie and
Tillie ;
and they lived at the bottom of a well.
...
"""
我们可以看到格式比较混乱,使用Beautiful Soup把这个格式进行处理
html_doc=""""<html><head><title>The Dormouse storytitle>head><body><p class="title"><b>The Dormouse storyb>p>< p class ="story" >Once upon a time there are three little sisters;and their names were<a href ="http://example.com/elsie" class ="sister" id="link1">Elsiea>,< a href = "http://example.com/lacie"class ="sister" id="link1" > Lacie < / a > and< a href = "http://example.com/tillie"class ="sister" id="link1" > Tillie < / a >;and they lived at the bottom of a well.< / p ><p class ="story">...p>"""from bs4 import BeautifulSoupsoup =BeautifulSoup(html_doc,'lxml')#lxml也是第三方库print(soup.prettify())
输出的格式就为标准的html格式
总结
通过查看源代码,数据比较混乱的时候,这个工具进行格式化处理
Beautiful Soup的功能-基本用法
Beautiful Soup的功能-基本用法html_doc=""""The Dormouse story</title>>
"title"
>< p class ="story" >Once upon a time there are three little sisters;and their names were"http://example.com/elsie" class =Lacie andTillie;and they lived at the bottom of a well.
...
"""from bs4 import BeautifulSoupsoup =BeautifulSoup(html_doc,'lxml')#lxml也是第三方库print(soup.prettify())#找到title标签print(soup.title)#找到title标签里的内容print(soup.title.string)#找到P标签print(soup.p)# 找到P标签class的名字# print(soup.p['class'])# 找到第一个a标签print(soup.a)# 找到所有a标签print(soup.find_all('a'))# 找到id为link3的标签print(soup.find(id="link3"))# 找到所有标签的链接for link in soup.find_all('a'): print(link.get('href'))# 找到文档中所有的文本内容print(soup.get_text())
Q&A
Lmxl和bs4的区别?
lxml 和bs4 本来就不是对等的关系, lxml是使用xml语法解析网页,如果实现内容提取要用到xpath, bs4默认是html解析,提取内容要用到bs4的内置函数
如果要给他们定义一下场景的话, lxml更像是引擎 ,bs4是引擎+工具,趋向简单可以使用bs4工具 ,趋向高性能可以使用bs4+lxml,相当于给bs4换了发动机, 趋向专业和高效可以使用 lxml+xpath
12月的第一天
2020年的最后一个月
2020年对于每一个人来说
都是有故事的一年
这个故事里面
有很多很多的情感交织
我有
你有吗