lxml安装_Beautiful Soup的安装和使用

不用正则也可匹配html语言,代替正则解析html的这个工具叫做Beautiful Soup(美味的汤?哈哈哈哈哈哈哈)

安装Beautiful Soup

Pip install Beautiful bs4

aa3374ad0d3eb29f1e4894c0bcfe4c68.png

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

Elsie,

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())

1ae609073519c845306d0f4951b1bea4.png

输出的格式就为标准的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())

30b7fc4a3a3a049a4033907f93553e89.png

Q&A

Lmxl和bs4的区别?

lxml 和bs4 本来就不是对等的关系, lxml是使用xml语法解析网页,如果实现内容提取要用到xpath, bs4默认是html解析,提取内容要用到bs4的内置函数

如果要给他们定义一下场景的话, lxml更像是引擎 ,bs4是引擎+工具,趋向简单可以使用bs4工具 ,趋向高性能可以使用bs4+lxml,相当于给bs4换了发动机, 趋向专业和高效可以使用 lxml+xpath

12月的第一天

2020年的最后一个月

2020年对于每一个人来说

都是有故事的一年

这个故事里面

有很多很多的情感交织

我有

你有吗

5b2057caa2ce235504a878d8ab23f818.png

1f6d3cb20d693c498dfcf51b7732217a.png

a8f2f2475840ab809b82e691d7e40edf.png

5f326f1f4a1643a938d3263e15f33021.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值