我需要安慰一件元素属性少于5的来唤醒什么意思

一个HTML元素和五个CSS属性的魔力一个HTML元素和五个CSS属性的魔力品酒话三江百家号假设我告诉你,我可以使用一个HTML元素和五个CSS属性实现下图的效果。而且这个效果没有使用任何一行SVG代码,也没有使用图像(只是在html元素上使用了background设置了一个背景图片,只是为了表明这个元素有一些透明的部分),同样也没有使用JavaScript代码。你一定会觉得很神奇,对吧!有好奇之心,对于我们做前端的同学而言,应该一直都有,只有这样才能做出很多我们一直以为实现不了的效果,比如接下来要介绍的内容。这篇文章将解释如何实现这个效果,然后展示如何通过添加一些动画来让效果变得更有趣。CSS中的渐变射线假设在HTML中刚好有一个元素:在CSS中,给这个元素设置一个尺寸,并且给它添加一个background,以便我们能看到它。同时使用border-radius把这个元素变成一个圆形。.rays{width:80height:80border-radius:50%;background: linear-gradient(#b53, #f90);}看到上面的代码,可能你会纳闷了,不是说五个属性和一个元素能实现文章开头的效果吗?现在都已经用掉四个属性了,只不过得到如下的一个效果。那么第五个属性是什么呢?其实就是带有repeating-conic-gradient()值的一个mask。假设我们想要20条射线。这意味着我们需要把圆分成20份,并且把这这个值赋值给一个变量:$p: 100% / 20,这个值包含了射线和射线间的间距。如下图所示:在这个示例中,我们让射线和射线间的间距相等,也就是射线和间距都是$p / 2的大小(也就是$p的一半),但我们完全可以根据自己所需,将其中任意一个变得更宽或更窄。我们希望在不透明部分(射线)的结束位置就是透明部分地起始位置。如果射线的停止位置是.5 * $p,那么这个间隙的起始位置就不会更大。但是,它可以是小的,它可以帮助我们保持简单,意味着我们可以把间距的起始位置设置为0。注意:与线性渐变和径向渐变不同的是,圆锥渐变的停止位置不能是无单位的。它们要么是百分比,要么是角度值。这意味着像使用transparent 0 $p是不起作用的,我们需要使用transparent 0% $p(我们也可以使用0deg替换0%,不管使用哪一个都不重要,重要的是不能是一个无单位的)。上面的效果在Edge是无效的。当聊到浏览器支持的时候,有几点需要注意:Edge还不支持在HTML元素上使用mask,尽管Edge已把这个功能列入到开发系列当中,而且它已经出现在about:flags中,但是到目前为止还没有做何事情。conic-gradient()仅在Blink内核的浏览器中得到了支持,而且也仅是实验性的特性,如果想要在Blink内核的浏览器中查看到效果,同样需要通过chrome://flags或opera://flags中开启Experimental Web Platform features。Safari也有支持,但到目前为止,Safari仍然依赖于Polyfill,就像Firefox一样。Webkit内核浏览器中的mask仍然需要添加-webkit-前缀。你会认为这没问题,因为我们使用的是Polyfill,而它依赖于-prefix-free,所以,如果我们使用Polyfill,我们需要在它之前引入-prefix-free。不幸的是,这比我们想的要复杂一点。主要是因为-prefix-free的运行需要通过特性检测,而在这种情况下常会失败,这是因为所有的浏览器都支持SVG不带前缀的mask属性。但是我们在HTML元素上使用了mask,而Wekit内核浏览器又需要-webkit-前缀的情部下,-prefix-free又不会添加,所以需要手动去添加:$nr:20; $p:100%/$ $m: repeating-conic-gradient(#000 0% .5*$p, transparent 0% $p); .rays {
-webkit-mask: $m;
mask: $m;}我想我们也可以使用Autoprefixeer,就算是我们需要使用-prefix-free,但总感觉使用这两种方法有点像是在用猎枪打死一只苍蝇一样。添加动画在Blink浏览器中已支持了了conic-gradient(),这样一来咱们就可以使用CSS自定义属性来替代Sass的变量(如果使用了Polyfill,那是不可以使用CSS自定义属性的)。在Blink内核的浏览器中使用Houdini可以让CSS自定义属性动态变化。为了添加动画部分的代码,我改变了mask中的渐变,给alpha值使用了CSS自定义属性。$m: repeating-conic-gradient(
rgba(#000, var(--a)) 0% .5*$p,
rgba(#000, calc(1 - var(--a))) 0% $p);然后我们通过CSS.registerProperty注册一个自定义属性--a:CSS.registerProperty({name:'--a',
syntax: '',
initialValue: 1;})最后在CSS中添加一个animation:.rays{animation: a 2s linea}@keyframes a {
}}最后的效果如下:效果看起来还不太好。但是,我们可以通过使用多个alpha值来让效果更好一些:$m: repeating-conic-gradient(
rgba(#000, var(--a0)) 0%, rgba(#000, var(--a1)) .5*$p,
rgba(#000, var(--a2)) 0%, rgba(#000, var(--a3)) $p);下一步是注册这些自定义属性:for(let i = 0; i < 4; i++) {
CSS.registerProperty({
name: `--a${i}`,
syntax: '',
initialValue: 1 - ~~(i/2)
})}最后,在CSS中调整animation:.rays {
animation: a 2
animation-name: a0, a1, a2, a3;
animation-timing-function:
cubic-bezier(.57, .05, .67, .19) /* easeInCubic */,
cubic-bezier(.21, .61, .35, 1); /* easeOutCubic */}@for $i from0 to 4 {
@keyframes a#{$i} {
--a#{$i}: #{floor($i/2)}
}}注意,由于我们将值设置为自定义属性,所以我们需要插入floor()函数。这个时候你看到的效果如下:现在效果看起来蛮不错了,但我们肯定还能做得更好,不是吗?让我们试着用CSS自定义属性来表示射线和间距的停止位置:$m: repeating-conic-gradient(#000 0% var(--p), transparent 0% $p);接来注册另一个自定义属性--p:CSS.registerProperty({name:'--p',
syntax: '',
initialValue: '0%'})我们在CSS的keyframe中使用这个自定义属性:.rays{animation: p .5s linear infinite alternate}@keyframes p {
--p: #{$p}
} }在这种情况下,效果更完美了。但是我们仍然可以通过在每次迭代之间水平地翻转整个东西来增加它的趣味性,这样它就会一直翻转到相反的部分。这意味着,当--p从0%到$p时和当--p从$p到0时,它是不会翻转。在CSS中可以通过transform: scaleX(-1)可以让一个元素进行水平翻转。由于我们希望在第一次迭代结束时应用这个翻转,然后在第二(反转)结束时删除它。这样我们可以在一个关键帧动画中使用它,并且配合steps()时间函数和两倍的animation-duration。$t: .5s;.rays{animation: p $t linear infinite alternate, s 2*$t steps(1)}@keyframes p {
--p: #{$p}
} }@keyframes s {
transform:scalex(-1);} }现在我们终于有一个看起来非常酷的效果了:渐变射线和波纹为了得到光线和波纹(涟漪)的效果,我们需要在mask上添加第二个渐变属性:repeating-radial-gradient():$nr: 20;$p: 100% / $$stop-list: #000 0% .5*$p, transparent 0% $p;$m: repeating-conic-gradient($stop-list),
repeating-radial-gradient(closest-side, $stop-list);.rays-ripples {
mask: $m;}遗憾的是,使用多个停止位置只在Blink内核浏览器中可用,并且是要开启了实验Web平台特性标记。虽然在HTML元素中使用mask时,conic-gradient()的Polyfill会覆盖repeating-conic-gradient(),但是不支持原生的conic-gradient()(Firefox、Safari、Blink浏览器没有启有标记),但在这些浏览器中,对于repeating-radial-gradient()部分到目前没有相应的解决方案。这意味着,我们不得不在代码中做一些重复的事情:$nr: 20;$p: 100% / $$stop-list: #000, #000 .5*$p, transparent 0%, transparent $p;$m: repeating-conic-gradient($stop-list),
repeating-radial-gradient(closest-side, $stop-list);.rays-ripples {
mask: $m;}虽然接近我们想要的效果,但还是没到那一步:为了得到我们想要的效果,需要使用mask-composite属性,并且将其设置exclude:$m: repeating-conic-gradient($stop-list) exclude,
repeating-radial-gradient(closest-side, $stop-list);注意,目前只有Firefox 53+ 支持了mask-composite,但是当它最终支持HTML元素的mask时,Edge应该加入进来了。如果你认为它看起来射线之间的间隙不相等,那是对的。这主要是由于Polyfill引起的问题。添加动画由于mask-composite现在只有 Firefox 53+中才能运行,而Firefox还不支持conic-gradient(),因此不能将CSS自定义属性用于repeating-conic-gradient()中(因为Fiefox仍然要借助于Polyfill,而有Polyfill的时候是不能使用CSS自定义属性)。但是可以在repeating-conic-gradient()中使用CSS自定义属性,即使我们不能使用CSS关键帧来控制动画,我们也可以使用JavaScript来控制。因为我们现在把CSS自定义属性用于repeating-radial-gradient(),但不能用于repeating-conic-gradient()(正如XOR效应也同样用于mask-composite,目前只有Firefox支持mask-composite,而Firefox又不支持原生的conic-gradient,所以会用到Polyfill来做降级处理,但Polyfill又不支持CSS自定义属性)。因此我们不能在mask的渐变中使用相同的$stop-list。但是,如果在没有一个通用的$stop-list的情况下要重写mask,那我们就可以利用这个机会使用不同的停止位置来实现两个渐变:// for conic gradient$nc: 20;$pc: 100%/$// for radial gradient$nr: 10;$pr: 100%/$在animation中有一个CSS自定义属性--a,就像第一射线动画的示例。我们还引入了--c0和--c1两个CSS自定义属性,这是因为我们不能有多个停止位置,以及我们想尽量避免重复:$m: repeating-conic-gradient(#000 .5*$pc, transparent 0% $pc) exclude,
repeating-radial-gradient(closest-side,
var(--c0), var(--c0) .5*$pr,
var(--c1) 0, var(--c1) $pr);body {
--a: 0;}.xor {
--c0: #{rgba(#000, var(--a))};
--c1: #{rgba(#000, calc(1 - var(--a)))};
mask: $m;}alpha自定义属性--a是我们来回动画的(从0到1,然后再回到0),并使用一点原生的JavaScript来实现这个效果。我们首先设置动画发生的帧数NF,当前帧索引f和当前动画方向dir:const NF = 50;let f = 0, dir = 1;在update()函数中,我们更新当前帧索引f,然后将当前的进度值(f/NF)设置为当前的alpha值--a。如果f已经达到NF的0位置,我们就需要改变方向。然后在下次刷新时再次调用update()函数。(functionupdate() {
document.body.style.setProperty('--a', (f/NF).toFixed(2));
if(!(f%NF)) dir *= -1;
requestAnimationFrame(update)})();这就是JavaScript全部内容。现在可以看到一个生动的效果:这是一个线性动画,alpha值--a被设置为f / NF。但是,我们可以将时间函数更改变其他的,正如我在前面的文章中所解释的那样,使用JavaScript来模拟CSS的时间函数。例如,如查我们想要一个ease-in的时间函数,将alpha值设置为easeIn(f / NF)而不是f / NF,下面就是easeIn()函数:functioneaseIn(k, e = 1.675) {return Math.pow(k, e)}可以在Codepen中的这个示例中看到使用ease-in时间函数的效果(只在Firefox 53+浏览器中可以看到效果)。如果你对我们如何得到这个函数感兴趣,那么可以查阅以前整理的相关文章。同样的方法也适用于easeOut()或easeInOut():functioneaseOut(k, e = 1.675) {return1 - Math.pow(1 - k, e)};functioneaseInOut(k) {return.5*(Math.sin((k - .5)*Math.PI) + 1)}因为我们使用的是JavaScript,所以我们可以添加一些交互事件,比如只有在点击或触摸时让动画动起来。let rID =functionstopAni() {
cancelAnimationFrame(rID);
rID = null};functionupdate() {if(!(f%NF)) {
stopAni();
rID = requestAnimationFrame(update)};可以添加click事件,停止任何可能正在运行的动画,反转动画方向dir和调用update()函数:addEventListener('click', e => {if(rID) stopAni();
dir *= -1;
update()}, false);因为当前帧索引f从0开始,向正方向走,在第一次点击时指向NF。因为我们在每次点击的时候都会改变方向,所以它的初始值必须是-1,所以在第一次点击时,它会被反转为+1。最终的效果可以在Codepen中查看。我们也可以给每个停止值使用不同的alpha的自定义属性,就像我们在射线的情况下一样:$m: repeating-conic-gradient(#000.5*$pc, transparent 0% $pc) exclude,
repeating-radial-gradient(closest-side,
rgba(#000, var(--a0)), rgba(#000, var(--a1)) .5*$pr,
rgba(#000, var(--a2)) 0, rgba(#000, var(--a3)) $pr);在JavaScript中,我们使用ease-in和ease-out的时间函数:const TFN = {'ease-in': function(k, e = 1.675) {return Math.pow(k, e)
'ease-out': function(k, e = 1.675) {return1 - Math.pow(1 - k, e)
}};在update()函数中,与第一个动效效果唯一的区别是,我们不只改变一个CSS自定义属性,我们现在要改变四个CSS自定义属性:--a0、--a1、--a2和--a3。可以在一个循环中使用ease-in,然后在偶数时使用ease-out函数。在前两项中,进度是f / NF给出,而在前两荐中,进度是1 - f / NF。这样就可以得到像下面这样的一个公式:(functionupdate() {
f +=for(var i = 0; i < 4; i++) {let j = ~~(i/2);
document.body.style.setProperty(
`--a${i}`,
TFN[i%2 ? 'ease-out' : 'ease-in'](j + Math.pow(-1, j)*f/NF).toFixed(2)
}if(!(f%NF)) dir *= -1;
requestAnimationFrame(update)})();最终的效果如下所示:就像圆锥渐变一样,我们也可以使不透明部分和mask中径向渐变的透明部分之间的停止位置产生动画效果。为些,我们使用一个CSS自定义属性--p,来表示这个停止位置 的进度:$m: repeating-conic-gradient(#000 .5*$pc, transparent 0% $pc) exclude,
repeating-radial-gradient(closest-side,
#000, #000 calc(var(--p)*#{$pr}),
transparent 0, transparent $pr);JavaScript和第一个alpha动画几乎是一样的,除了我们不更新--a自定义属性,还会更新--p自定义属性,以及使用一个ease-in-out函数:functioneaseInOut(k) {return.5*(Math.sin((k - .5)*Math.PI) + 1)};(functionupdate() {
document.body.style.setProperty('--p', easeInOut(f/NF).toFixed(2));})();我们可以让效果更好一些,如果我们在不透明条前面加上一条透明条,就需要新增一个新的停止位置的CSS自定义属性--p0。这个透明条会变成不透明条:$m: repeating-conic-gradient(#000 .5*$pc, transparent 0% $pc) exclude,
repeating-radial-gradient(closest-side,
transparent, transparent calc(var(--p0)*#{$pr}), #000, #000 calc(var(--p1)*#{$pr}),
transparent 0, transparent $pr);在JavaScript中,我们现在需要激活两个CSS自定义属性:--p0和--p1。第一个使用ease-in时间函数,第二个使用ease-out时间函数。我们也不再改变动画的方向:const NF = 120,
TFN = {'ease-in': function(k, e = 1.675) {return Math.pow(k, e)
'ease-out': function(k, e = 1.675) {return1 - Math.pow(1 - k, e)
};let f = 0;(functionupdate() {
f = (f + 1)%NF;for(var i = 0; i < 2; i++)
document.body.style.setProperty(`--p${i}`, TFN[i ? 'ease-out' : 'ease-in'](f/NF);
requestAnimationFrame(update)})();最终的效果如下:本文由百家号作者上传并发布,百家号仅提供信息发布平台。文章仅代表作者个人观点,不代表百度立场。未经作者许可,不得转载。品酒话三江百家号最近更新:简介:相信时间的力量,可以冲淡很多东西。作者最新文章相关文章博主录制的Python3爬虫视频教程已发布!详情请戳!希望大家支持!非常感谢!
> Python爬虫利器二之Beautiful Soup的用法
上一节我们介绍了正则表达式,它的内容其实还是蛮多的,如果一个正则匹配稍有差池,那可能程序就处在永久的循环之中,而且有的小伙伴们也对写正则表达式的写法用得不熟练,没关系,我们还有一个更强大的工具,叫Beautiful Soup,有了它我们可以很方便地提取出HTML或XML标签中的内容,实在是方便,这一节就让我们一起来感受一下Beautiful Soup的强大吧。
1. Beautiful Soup的简介
简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:
Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。
Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。
废话不多说,我们来试一下吧~
2. Beautiful Soup 安装
Beautiful Soup 3 目前已经停止开发,推荐在现在的项目中使用Beautiful Soup 4,不过它已经被移植到BS4了,也就是说导入时我们需要 import bs4 。所以这里我们用的版本是 Beautiful Soup 4.3.2 (简称BS4),另外据说 BS4 对 Python3 的支持不够好,不过我用的是 Python2.7.7,如果有小伙伴用的是 Python3 版本,可以考虑下载 BS3 版本。
可以利用 pip 或者 easy_install 来安装,以下两种方法均可
easy_install beautifulsoup4
easy_install beautifulsoup4
pip install beautifulsoup4
pip install beautifulsoup4
如果想安装最新的版本,请直接下载安装包来手动安装,也是十分方便的方法。在这里我安装的是 Beautiful Soup 4.3.2
下载完成之后解压
运行下面的命令即可完成安装
sudo python setup.py install
sudo python setup.py install
然后需要安装 lxml
easy_install lxml
easy_install lxml
pip install lxml
pip install lxml
另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:
easy_install html5lib
easy_install html5lib
pip install html5lib
pip install html5lib
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。
&thead&#8221;&
Python标准库
BeautifulSoup(markup, &#8220;html.parser&#8221;)
Python的内置标准库
执行速度适中
文档容错能力强
Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
lxml HTML 解析器
BeautifulSoup(markup, &#8220;lxml&#8221;)
文档容错能力强
需要安装C语言库
lxml XML 解析器
BeautifulSoup(markup, [&#8220;lxml&#8221;, &#8220;xml&#8221;])BeautifulSoup(markup, &#8220;xml&#8221;)
唯一支持XML的解析器
需要安装C语言库
BeautifulSoup(markup, &#8220;html5lib&#8221;)
最好的容错性
以浏览器的方式解析文档
生成HTML5格式的文档
不依赖外部扩展
3. 开启Beautiful Soup 之旅
在这里先分享官方文档链接,不过内容是有些多,也不够条理,在此本文章做一下整理方便大家参考。
4. 创建 Beautiful Soup 对象
首先必须要导入 bs4 库
from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
我们创建一个字符串,后面的例子我们便会用它来演示
html = """
&html&&head&&title&The Dormouse's story&/title&&/head&
&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&
&p class="story"&Once upon a time there were
and their names were
&a href="http://example.com/elsie" class="sister" id="link1"&&!-- Elsie --&&/a&,
&a href="http://example.com/lacie" class="sister" id="link2"&Lacie&/a& and
&a href="http://example.com/tillie" class="sister" id="link3"&Tillie&/a&;
and they lived at the bottom of a well.&/p&
&p class="story"&...&/p&
1234567891011
html = """&html&&head&&title&The Dormouse's story&/title&&/head&&body&&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&&p class="story"&Once upon a time there were
and their names were&a href="http://example.com/elsie" class="sister" id="link1"&&!-- Elsie --&&/a&,&a href="http://example.com/lacie" class="sister" id="link2"&Lacie&/a& and&a href="http://example.com/tillie" class="sister" id="link3"&Tillie&/a&;and they lived at the bottom of a well.&/p&&p class="story"&...&/p&"""
创建 beautifulsoup 对象
soup = BeautifulSoup(html)
soup = BeautifulSoup(html)
另外,我们还可以用本地 HTML 文件来创建对象,例如
soup = BeautifulSoup(open('index.html'))
soup = BeautifulSoup(open('index.html'))
上面这句代码便是将本地 index.html 文件打开,用它来创建 soup 对象
下面我们来打印一下 soup 对象的内容,格式化输出
print soup.prettify()
print soup.prettify()
The Dormouse's story
&p class="title" name="dromouse"&
The Dormouse's story
&p class="story"&
Once upon a time there were
and their names were
&a class="sister" href="http://example.com/elsie" id="link1"&
&!-- Elsie --&
&a class="sister" href="http://example.com/lacie" id="link2"&
&a class="sister" href="http://example.com/tillie" id="link3"&
and they lived at the bottom of a well.
&p class="story"&
&html& &head&&&&title&&& The Dormouse's story&&&/title&
以上便是输出结果,格式化打印出了它的内容,这个函数经常用到,小伙伴们要记好咯。
5. 四大对象种类
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
NavigableString
BeautifulSoup
下面我们进行一一介绍
Tag 是什么?通俗点讲就是 HTML 中的一个个标签,例如
&title&The Dormouse's story&/title&
&title&The Dormouse's story&/title&
&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&
&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&
上面的 title a 等等 HTML 标签加上里面包括的内容就是 Tag,下面我们来感受一下怎样用 Beautiful Soup 来方便地获取 Tags
下面每一段代码中注释部分即为运行结果
print soup.title
#&title&The Dormouse's story&/title&
print soup.title#&title&The Dormouse's story&/title&
print soup.head
#&head&&title&The Dormouse's story&/title&&/head&
print soup.head#&head&&title&The Dormouse's story&/title&&/head&
print soup.a
#&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&
print soup.a#&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&
print soup.p
#&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&
print soup.p#&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&
我们可以利用 soup加标签名轻松地获取这些标签的内容,是不是感觉比正则表达式方便多了?不过有一点是,它查找的是在所有内容中的第一个符合要求的标签,如果要查询所有的标签,我们在后面进行介绍。
我们可以验证一下这些对象的类型
print type(soup.a)
#&class 'bs4.element.Tag'&
print type(soup.a)#&class 'bs4.element.Tag'&
对于 Tag,它有两个重要的属性,是 name 和 attrs,下面我们分别来感受一下
print soup.name
print soup.head.name
#[document]
print soup.nameprint soup.head.name#[document]#head
soup 对象本身比较特殊,它的 name 即为 [document],对于其他内部标签,输出的值便为标签本身的名称。
print soup.p.attrs
#{'class': ['title'], 'name': 'dromouse'}
print soup.p.attrs#{'class': ['title'], 'name': 'dromouse'}
在这里,我们把 p 标签的所有属性打印输出了出来,得到的类型是一个字典。
如果我们想要单独获取某个属性,可以这样,例如我们获取它的 class 叫什么
print soup.p['class']
#['title']
print soup.p['class']#['title']
还可以这样,利用get方法,传入属性的名称,二者是等价的
print soup.p.get('class')
#['title']
print soup.p.get('class')#['title']
我们可以对这些属性和内容等等进行修改,例如
soup.p['class']="newClass"
print soup.p
#&p class="newClass" name="dromouse"&&b&The Dormouse's story&/b&&/p&
soup.p['class']="newClass"print soup.p#&p class="newClass" name="dromouse"&&b&The Dormouse's story&/b&&/p&
还可以对这个属性进行删除,例如
del soup.p['class']
print soup.p
#&p name="dromouse"&&b&The Dormouse's story&/b&&/p&
del soup.p['class']print soup.p#&p name="dromouse"&&b&The Dormouse's story&/b&&/p&
不过,对于修改删除的操作,不是我们的主要用途,在此不做详细介绍了,如果有需要,请查看前面提供的官方文档
(2)NavigableString
既然我们已经得到了标签的内容,那么问题来了,我们要想获取标签内部的文字怎么办呢?很简单,用 .string 即可,例如
print soup.p.string
#The Dormouse's story
print soup.p.string#The Dormouse's story
这样我们就轻松获取到了标签里面的内容,想想如果用正则表达式要多麻烦。它的类型是一个 NavigableString,翻译过来叫 可以遍历的字符串,不过我们最好还是称它英文名字吧。
来检查一下它的类型
print type(soup.p.string)
#&class 'bs4.element.NavigableString'&
print type(soup.p.string)#&class 'bs4.element.NavigableString'&
(3)BeautifulSoup
BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下
print type(soup.name)
#&type 'unicode'&
print soup.name
# [document]
print soup.attrs
#{} 空字典
print type(soup.name)#&type 'unicode'&print soup.name # [document]print soup.attrs #{} 空字典
(4)Comment
Comment 对象是一个特殊类型的 NavigableString 对象,其实输出的内容仍然不包括注释符号,但是如果不好好处理它,可能会对我们的文本处理造成意想不到的麻烦。
我们找一个带注释的标签
print soup.a
print soup.a.string
print type(soup.a.string)
print soup.aprint soup.a.stringprint type(soup.a.string)
运行结果如下
&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&
&class 'bs4.element.Comment'&
&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a& Elsie &class 'bs4.element.Comment'&
a 标签里的内容实际上是注释,但是如果我们利用 .string 来输出它的内容,我们发现它已经把注释符号去掉了,所以这可能会给我们带来不必要的麻烦。
另外我们打印输出下它的类型,发现它是一个 Comment 类型,所以,我们在使用前最好做一下判断,判断代码如下
if type(soup.a.string)==bs4.element.Comment:
print soup.a.string
if type(soup.a.string)==bs4.element.Comment:&&&&print soup.a.string
上面的代码中,我们首先判断了它的类型,是否为 Comment 类型,然后再进行其他操作,如打印输出。
6. 遍历文档树
(1)直接子节点
要点:.contents
tag 的 .content 属性可以将tag的子节点以列表的方式输出
print soup.head.contents
#[&title&The Dormouse's story&/title&]
print soup.head.contents #[&title&The Dormouse's story&/title&]
输出方式为列表,我们可以用列表索引来获取它的某一个元素
print soup.head.contents[0]
#&title&The Dormouse's story&/title&
print soup.head.contents[0]#&title&The Dormouse's story&/title&
它返回的不是一个 list,不过我们可以通过遍历获取所有子节点。
我们打印输出 .children 看一下,可以发现它是一个 list 生成器对象
print soup.head.children
#&listiterator object at 0x7f&
print soup.head.children#&listiterator object at 0x7f&
我们怎样获得里面的内容呢?很简单,遍历一下就好了,代码及结果如下
for child in
soup.body.children:
print child
for child in&&soup.body.children:&&&&print child
&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&
&p class="story"&Once upon a time there were
and their names were
&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&,
&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a& and
&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&;
and they lived at the bottom of a well.&/p&
&p class="story"&...&/p&
&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&&&p class="story"&Once upon a time there were three little sisters; and their names were&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&,&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a& and
(2)所有子孙节点
知识点:.descendants 属性
.descendants
.contents 和 .children 属性仅包含tag的直接子节点,.descendants 属性可以对所有tag的子孙节点进行递归循环,和 children类似,我们也需要遍历获取其中的内容。
for child in soup.descendants:
print child
for child in soup.descendants:&&&&print child
运行结果如下,可以发现,所有的节点都被打印出来了,先生最外层的 HTML标签,其次从 head 标签一个个剥离,以此类推。
&html&&head&&title&The Dormouse's story&/title&&/head&
&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&
&p class="story"&Once upon a time there were
and their names were
&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&,
&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a& and
&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&;
and they lived at the bottom of a well.&/p&
&p class="story"&...&/p&
&/body&&/html&
&head&&title&The Dormouse's story&/title&&/head&
&title&The Dormouse's story&/title&
The Dormouse's story
&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&
&p class="story"&Once upon a time there were
and their names were
&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&,
&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a& and
&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&;
and they lived at the bottom of a well.&/p&
&p class="story"&...&/p&
&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&
&b&The Dormouse's story&/b&
The Dormouse's story
&p class="story"&Once upon a time there were
and their names were
&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&,
&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a& and
&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&;
and they lived at the bottom of a well.&/p&
Once upon a time there were
and their names were
&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&
&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&
&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&
and they lived at the bottom of a well.
&p class="story"&...&/p&
&html&&head&&title&The Dormouse's story&/title&&/head&&body&&p class="title" name="dromouse"&&b&The Dormouse's story&/b&&/p&&p class="story"&Once upon a time there were three little sisters; and their names were&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&,
(3)节点内容
知识点:.string 属性
如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点。如果一个tag仅有一个子节点,那么这个tag也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同。
通俗点说就是:如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容。例如
print soup.head.string
#The Dormouse's story
print soup.title.string
#The Dormouse's story
print soup.head.string#The Dormouse's storyprint soup.title.string#The Dormouse's story
如果tag包含了多个子节点,tag就无法确定,string 方法应该调用哪个子节点的内容, .string 的输出结果是 None
print soup.html.string
print soup.html.string# None
(4)多个内容
知识点: .strings
.stripped_strings 属性
获取多个内容,不过需要遍历获取,比如下面的例子
for string in soup.strings:
print(repr(string))
# u"The Dormouse's story"
# u"The Dormouse's story"
# u'Once upon a time there were
and their names were\n'
# u'Elsie'
# u'Lacie'
# u' and\n'
# u'Tillie'
# u';\nand they lived at the bottom of a well.'
12345678910111213141516
for string in soup.strings:&&&&print(repr(string))&&&&# u"The Dormouse's story"&&&&# u'\n\n'&&&&# u"The Dormouse's story"&&&&# u'\n\n'&&&&# u'Once upon a time there were
and their names were\n'&&&&# u'Elsie'&&&&# u',\n'&&&&# u'Lacie'&&&&# u' and\n'&&&&# u'Tillie'&&&&# u';\nand they lived at the bottom of a well.'&&&&# u'\n\n'&&&&# u'...'&&&&# u'\n'
.stripped_strings
输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容
for string in soup.stripped_strings:
print(repr(string))
# u"The Dormouse's story"
# u"The Dormouse's story"
# u'Once upon a time there were
and their names were'
# u'Elsie'
# u'Lacie'
# u'Tillie'
# u';\nand they lived at the bottom of a well.'
123456789101112
for string in soup.stripped_strings:&&&&print(repr(string))&&&&# u"The Dormouse's story"&&&&# u"The Dormouse's story"&&&&# u'Once upon a time there were
and their names were'&&&&# u'Elsie'&&&&# u','&&&&# u'Lacie'&&&&# u'and'&&&&# u'Tillie'&&&&# u';\nand they lived at the bottom of a well.'&&&&# u'...'
(5)父节点
知识点: .parent 属性
p = soup.p
print p.parent.name
p = soup.pprint p.parent.name#body
content = soup.head.title.string
print content.parent.name
content = soup.head.title.stringprint content.parent.name#title
(6)全部父节点
知识点:.parents 属性
通过元素的 .parents 属性可以递归得到元素的所有父辈节点,例如
content = soup.head.title.string
for parent in
content.parents:
print parent.name
content = soup.head.title.stringfor parent in&&content.parents:&&&&print parent.name
[document]
titleheadhtml[document]
(7)兄弟节点
知识点:.next_sibling
.previous_sibling 属性
兄弟节点可以理解为和本节点处在统一级的节点,.next_sibling 属性获取了该节点的下一个兄弟节点,.previous_sibling 则与之相反,如果节点不存在,则返回 None
注意:实际文档中的tag的 .next_sibling 和 .previous_sibling 属性通常是字符串或空白,因为空白或者换行也可以被视作一个节点,所以得到的结果可能是空白或者换行
print soup.p.next_sibling
实际该处为空白
print soup.p.prev_sibling
没有前一个兄弟节点,返回 None
print soup.p.next_sibling.next_sibling
#&p class="story"&Once upon a time there were
and their names were
#&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&,
#&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a& and
#&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&;
#and they lived at the bottom of a well.&/p&
#下一个节点的下一个兄弟节点是我们可以看到的节点
1234567891011
print soup.p.next_sibling#&&&&&& 实际该处为空白print soup.p.prev_sibling#None&& 没有前一个兄弟节点,返回 Noneprint soup.p.next_sibling.next_sibling#&p class="story"&Once upon a time there were
and their names were#&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&,#&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a& and#&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&;#and they lived at the bottom of a well.&/p&#下一个节点的下一个兄弟节点是我们可以看到的节点
(8)全部兄弟节点
知识点:.next_siblings
.previous_siblings 属性
通过 .next_siblings 和 .previous_siblings 属性可以对当前节点的兄弟节点迭代输出
for sibling in soup.a.next_siblings:
print(repr(sibling))
# &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&
# u' and\n'
# &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&
# u'; and they lived at the bottom of a well.'
for sibling in soup.a.next_siblings:&&&&print(repr(sibling))&&&&# u',\n'&&&&# &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&&&&&# u' and\n'&&&&# &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&&&&&# u'; and they lived at the bottom of a well.'&&&&# None
(9)前后节点
知识点:.next_element
.previous_element 属性
与 .next_sibling
.previous_sibling 不同,它并不是针对于兄弟节点,而是在所有节点,不分层次
比如 head 节点为
&head&&title&The Dormouse's story&/title&&/head&
&head&&title&The Dormouse's story&/title&&/head&
那么它的下一个节点便是 title,它是不分层次关系的
print soup.head.next_element
#&title&The Dormouse's story&/title&
print soup.head.next_element#&title&The Dormouse's story&/title&
(10)所有前后节点
知识点:.next_elements
.previous_elements 属性
通过 .next_elements 和 .previous_elements 的迭代器就可以向前或向后访问文档的解析内容,就好像文档正在被解析一样
for element in last_a_tag.next_elements:
print(repr(element))
# u'Tillie'
# u';\nand they lived at the bottom of a well.'
# &p class="story"&...&/p&
for element in last_a_tag.next_elements:&&&&print(repr(element))# u'Tillie'# u';\nand they lived at the bottom of a well.'# u'\n\n'# &p class="story"&...&/p&# u'...'# u'\n'# None
以上是遍历文档树的基本用法。
7.搜索文档树
(1)find_all( name , attrs , recursive , text , **kwargs )
find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件
1)name 参数
name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉
A.传字符串
最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的&b&标签
soup.find_all('b')
# [&b&The Dormouse's story&/b&]
soup.find_all('b')# [&b&The Dormouse's story&/b&]
print soup.find_all('a')
#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&, &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&, &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
print soup.find_all('a')#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&, &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&, &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
B.传正则表达式
如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示&body&和&b&标签都应该被找到
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
import refor tag in soup.find_all(re.compile("^b")):&&&&print(tag.name)# body# b
如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有&a&标签和&b&标签
soup.find_all(["a", "b"])
# [&b&The Dormouse's story&/b&,
&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&,
&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&,
&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
soup.find_all(["a", "b"])# [&b&The Dormouse's story&/b&,#&&&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&,#&&&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&,#&&&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点
for tag in soup.find_all(True):
print(tag.name)
1234567891011
for tag in soup.find_all(True):&&&&print(tag.name)# html# head# title# body# p# b# p# a# a
如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数
,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性,那么将返回 True:
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
def has_class_but_no_id(tag):&&&&return tag.has_attr('class') and not tag.has_attr('id')
将这个方法作为参数传入 find_all() 方法,将得到所有&p&标签:
soup.find_all(has_class_but_no_id)
# [&p class="title"&&b&The Dormouse's story&/b&&/p&,
&p class="story"&Once upon a time there were...&/p&,
&p class="story"&...&/p&]
soup.find_all(has_class_but_no_id)# [&p class="title"&&b&The Dormouse's story&/b&&/p&,#&&&p class="story"&Once upon a time there were...&/p&,#&&&p class="story"&...&/p&]
2)keyword 参数
注意:如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性
soup.find_all(id='link2')
# [&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&]
soup.find_all(id='link2')# [&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&]
如果传入 href 参数,Beautiful Soup会搜索每个tag的”href”属性
soup.find_all(href=re.compile("elsie"))
# [&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&]
soup.find_all(href=re.compile("elsie"))# [&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&]
使用多个指定名字的参数可以同时过滤tag的多个属性
soup.find_all(href=re.compile("elsie"), id='link1')
# [&a class="sister" href="http://example.com/elsie" id="link1"&three&/a&]
soup.find_all(href=re.compile("elsie"), id='link1')# [&a class="sister" href="http://example.com/elsie" id="link1"&three&/a&]
在这里我们想用 class 过滤,不过 class 是 python 的关键词,这怎么办?加个下划线就可以
soup.find_all("a", class_="sister")
# [&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&,
&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&,
&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
soup.find_all("a", class_="sister")# [&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&,#&&&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&,#&&&a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性
data_soup = BeautifulSoup('&div data-foo="value"&foo!&/div&')
data_soup.find_all(data-foo="value")
# SyntaxError: keyword can't be an expression
data_soup = BeautifulSoup('&div data-foo="value"&foo!&/div&')data_soup.find_all(data-foo="value")# SyntaxError: keyword can't be an expression
但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag
data_soup.find_all(attrs={"data-foo": "value"})
# [&div data-foo="value"&foo!&/div&]
data_soup.find_all(attrs={"data-foo": "value"})# [&div data-foo="value"&foo!&/div&]
3)text 参数
通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True
soup.find_all(text="Elsie")
# [u'Elsie']
soup.find_all(text=["Tillie", "Elsie", "Lacie"])
# [u'Elsie', u'Lacie', u'Tillie']
soup.find_all(text=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"]
soup.find_all(text="Elsie")# [u'Elsie']&soup.find_all(text=["Tillie", "Elsie", "Lacie"])# [u'Elsie', u'Lacie', u'Tillie']&soup.find_all(text=re.compile("Dormouse"))[u"The Dormouse's story", u"The Dormouse's story"]
4)limit 参数
find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.
文档树中有3个tag符合搜索条件,但结果只返回了2个,因为我们限制了返回数量
soup.find_all("a", limit=2)
# [&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&,
&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&]
soup.find_all("a", limit=2)# [&a class="sister" href="http://example.com/elsie" id="link1"&Elsie&/a&,#&&&a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&]
5)recursive 参数
调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .
一段简单的文档:
The Dormouse's story
&html& &head&&&&title&&& The Dormouse's story&&&/title& &/head&...
是否使用 recursive 参数的搜索结果:
soup.html.find_all("title")
# [&title&The Dormouse's story&/title&]
soup.html.find_all("title", recursive=False)
soup.html.find_all("title")# [&title&The Dormouse's story&/title&]&soup.html.find_all("title", recursive=False)# []
(2)find( name , attrs , recursive , text , **kwargs )
它与 find_all() 方法唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果
(3)find_parents()
find_parent()
find_all() 和 find() 只搜索当前节点的所有子节点,孙子节点等. find_parents() 和 find_parent() 用来搜索当前节点的父辈节点,搜索方法与普通tag的搜索方法相同,搜索文档搜索文档包含的内容
(4)find_next_siblings()
find_next_sibling()
这2个方法通过 .next_siblings 属性对当 tag 的所有后面解析的兄弟 tag 节点进行迭代, find_next_siblings() 方法返回所有符合条件的后面的兄弟节点,find_next_sibling() 只返回符合条件的后面的第一个tag节点
(5)find_previous_siblings()
find_previous_sibling()
这2个方法通过 .previous_siblings 属性对当前 tag 的前面解析的兄弟 tag 节点进行迭代, find_previous_siblings() 方法返回所有符合条件的前面的兄弟节点, find_previous_sibling() 方法返回第一个符合条件的前面的兄弟节点
(6)find_all_next()
find_next()
这2个方法通过 .next_elements 属性对当前 tag 的之后的 tag 和字符串进行迭代, find_all_next() 方法返回所有符合条件的节点, find_next() 方法返回第一个符合条件的节点
(7)find_all_previous() 和 find_previous()
这2个方法通过 .previous_elements 属性对当前节点前面的 tag 和字符串进行迭代, find_all_previous() 方法返回所有符合条件的节点, find_previous()方法返回第一个符合条件的节点
注:以上(2)(3)(4)(5)(6)(7)方法参数用法与 find_all() 完全相同,原理均类似,在此不再赘述。
8.CSS选择器
我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list
(1)通过标签名查找
print soup.select('title')
#[&title&The Dormouse's story&/title&]
print soup.select('title') #[&title&The Dormouse's story&/title&]
print soup.select('a')
#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&, &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&, &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
print soup.select('a')#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&, &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&, &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
print soup.select('b')
#[&b&The Dormouse's story&/b&]
print soup.select('b')#[&b&The Dormouse's story&/b&]
(2)通过类名查找
print soup.select('.sister')
#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&, &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&, &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
print soup.select('.sister')#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&, &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&, &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
(3)通过 id 名查找
print soup.select('#link1')
#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&]
print soup.select('#link1')#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&]
(4)组合查找
组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开
print soup.select('p #link1')
#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&]
print soup.select('p #link1')#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&]
直接子标签查找
print soup.select("head & title")
#[&title&The Dormouse's story&/title&]
print soup.select("head & title")#[&title&The Dormouse's story&/title&]
(5)属性查找
查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。
print soup.select('a[class="sister"]')
#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&, &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&, &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
print soup.select('a[class="sister"]')#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&, &a class="sister" href="http://example.com/lacie" id="link2"&Lacie&/a&, &a class="sister" href="http://example.com/tillie" id="link3"&Tillie&/a&]
print soup.select('a[href="http://example.com/elsie"]')
#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&]
print soup.select('a[href="http://example.com/elsie"]')#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&]
同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格
print soup.select('p a[href="http://example.com/elsie"]')
#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&]
print soup.select('p a[href="http://example.com/elsie"]')#[&a class="sister" href="http://example.com/elsie" id="link1"&&!-- Elsie --&&/a&]
以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容。
soup = BeautifulSoup(html, 'lxml')
print type(soup.select('title'))
print soup.select('title')[0].get_text()
for title in soup.select('title'):
print title.get_text()
soup = BeautifulSoup(html, 'lxml')print type(soup.select('title'))print soup.select('title')[0].get_text()&for title in soup.select('title'):&&&&print title.get_text()
好,这就是另一种与 find_all 方法有异曲同工之妙的查找方法,是不是感觉很方便?
本篇内容比较多,把 Beautiful Soup 的方法进行了大部分整理和总结,不过这还不算完全,仍然有 Beautiful Soup 的修改删除功能,不过这些功能用得比较少,只整理了查找提取的方法,希望对大家有帮助!小伙伴们加油!
熟练掌握了 Beautiful Soup,一定会给你带来太多方便,加油吧!
转载请注明: &
or分享 (0)
我的个人微信公众号,联系我请直接在公众号留言即可~
扫码或搜索:进击的Coder
进击的Coder
微信公众号
扫一扫关注
想结交更多的朋友吗?
来进击的Coder瞧瞧吧
进击的Coder
进击的Coder灌水太多?
这里是纯粹的技术领地
激进的Coder
您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请狠狠点击下面的

我要回帖

更多关于 我需要你k.will 的文章

 

随机推荐