BeautifulSoup支持大部分的CSS选择器,其语法为:向tag或soup对象的.select()方法中传入字符串参数,选择的结果以列表形式返回。

  tag.select("string")

  BeautifulSoup.select("string")

源代码示例:

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 three little sisters; and their names were
<a class="mysis" href="http://example.com/elsie" id="link1">
<b>the first b tag<b>
Elsie
</a>,
<a class="mysis" href="http://example.com/lacie" id="link2" myname="kong">
Lacie
</a>and
<a class="mysis" href="http://example.com/tillie" id="link3">
Tillie
</a>;and they lived at the bottom of a well.
</p>
<p class="story">
myStory
<a>the end a tag</a>
</p>
<a>the p tag sibling</a>
</body>
</html>
"""
soup = BeautifulSoup(html,'lxml')

  1、通过标签选择

# 选择所有title标签
soup.select("title")
# 选择所有p标签中的第三个标签
soup.select("p:nth-of-type(3)") 相当于soup.select(p)[2]
# 选择body标签下的所有a标签
soup.select("body a")
# 选择body标签下的直接a子标签
soup.select("body > a")
# 选择id=link1后的所有兄弟节点标签
soup.select("#link1 ~ .mysis")
# 选择id=link1后的下一个兄弟节点标签
soup.select("#link1 + .mysis")

  2、通过类名查找

# 选择a标签,其类属性为mysis的标签
soup.select("a.mysis")

  3、通过id查找

# 选择a标签,其id属性为link1的标签
soup.select("a#link1")

  4、通过【属性】查找,当然也适用于class

# 选择a标签,其属性中存在myname的所有标签
soup.select("a[myname]")
# 选择a标签,其属性href=http://example.com/lacie的所有标签
soup.select("a[href='http://example.com/lacie']")
# 选择a标签,其href属性以http开头
soup.select('a[href^="http"]')
# 选择a标签,其href属性以lacie结尾
soup.select('a[href$="lacie"]')
# 选择a标签,其href属性包含.com
soup.select('a[href*=".com"]')
# 从html中排除某标签,此时soup中不再有script标签
[s.extract() for s in soup('script')]
# 如果想排除多个呢
[s.extract() for s in soup(['script','fram']

  

  5、获取文本及属性

html_doc = """<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; 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>;
</p>
and they lived at the bottom of a well.
<p class="story">...</p>
</body>
"""
from bs4 import BeautifulSoup
'''
以列表的形式返回
'''
soup = BeautifulSoup(html_doc, 'html.parser')
s = soup.select('p.story')
s[].get_text() # p节点及子孙节点的文本内容
s[].get_text("|") # 指定文本内容的分隔符
s[].get_text("|", strip=True) # 去除文本内容前后的空白
print(s[].get("class")) # p节点的class属性值列表(除class外都是返回字符串)

  6、UnicodeDammit.detwingle() 方法只能解码包含在UTF-8编码中的Windows-1252编码内容,

new_doc = UnicodeDammit.detwingle(doc)
print(new_doc.decode("utf8"))
# ☃☃☃“I like snowmen!”

在创建 BeautifulSoup 或 UnicodeDammit 对象前一定要先对文档调用 UnicodeDammit.detwingle() 确保文档的编码方式正确.如果尝试去解析一段包含Windows-1252编码的UTF-8文档,就会得到一堆乱码,比如: ☃☃☃“I like snowmen!”.

  

  7、其它:

html_doc = """<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; 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>;
</p>
and they lived at the bottom of a well.
<p class="story">...</p>
</body>
"""
from bs4 import BeautifulSoup
'''
以列表的形式返回
'''
soup = BeautifulSoup(html_doc, 'html.parser')
soup.select('title') # title标签
soup.select("p:nth-of-type(3)") # 第三个p节点
soup.select('body a') # body下的所有子孙a节点
soup.select('p > a') # 所有p节点下的所有a直接节点
soup.select('p > #link1') # 所有p节点下的id=link1的直接子节点
soup.select('#link1 ~ .sister') # id为link1的节点后面class=sister的所有兄弟节点
soup.select('#link1 + .sister') # id为link1的节点后面class=sister的第一个兄弟节点
soup.select('.sister') # class=sister的所有节点
soup.select('[class="sister"]') # class=sister的所有节点
soup.select("#link1") # id=link1的节点
soup.select("a#link1") # a节点,且id=link1的节点
soup.select('a[href]') # 所有的a节点,有href属性
soup.select('a[href="http://example.com/elsie"]') # 指定href属性值的所有a节点
soup.select('a[href^="http://example.com/"]') # href属性以指定值开头的所有a节点
soup.select('a[href$="tillie"]') # href属性以指定值结尾的所有a节点
soup.select('a[href*=".com/el"]') # 支持正则匹配

beautifulsoup之CSS选择器的更多相关文章

  1. 【网络爬虫入门04】彻底掌握BeautifulSoup的CSS选择器

    [网络爬虫入门04]彻底掌握BeautifulSoup的CSS选择器 广东职业技术学院  欧浩源 2017-10-21 1.引言 目前,除了官方文档之外,市面上及网络详细介绍BeautifulSoup ...

  2. bs4 CSS选择器

    #https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find-all #beautifulSoup可以解析HTML ...

  3. 爬虫之BeautifulSoup, CSS

    1. Beautiful Soup的简介 2. Beautiful Soup 安装 可以利用 pip 或者 easy_install 来安装,以下两种方法均可 easy_install beautif ...

  4. 六、CSS 选择器:BeautifulSoup4

    和 lxml 一样,Beautiful Soup 也是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据. lxml 只会局部遍历,而Beautiful Soup 是基 ...

  5. 如何利用CSS选择器抓取京东网商品信息

    前几天小编分别利用Python正则表达式.BeautifulSoup.Xpath分别爬取了京东网商品信息,今天小编利用CSS选择器来为大家展示一下如何实现京东商品信息的精准匹配~~ CSS选择器 目前 ...

  6. 使用requests爬取梨视频、bilibili视频、汽车之家,bs4遍历文档树、搜索文档树,css选择器

    今日内容概要 使用requests爬取梨视频 requests+bs4爬取汽车之家 bs4遍历文档树 bs4搜索文档树 css选择器 内容详细 1.使用requests爬取梨视频 # 模拟发送http ...

  7. 前端极易被误导的css选择器权重计算及css内联样式的妙用技巧

    记得大学时候,专业课的网页设计书籍里面讲过css选择器权重的计算:id是100,class是10,html标签是5等等,然后全部加起来的和进行比较... 我只想说:真是误人子弟,害人不浅! 最近,在前 ...

  8. css选择器

    常用css选择器,希望对大家有所帮助,不喜勿喷. 1.*:通用选择器 * { margin: 0; padding: 0; } 选择页面上的全部元素,通常用于清除浏览器默认样式,不推荐使用. 2.#i ...

  9. dynamic-css 动态 CSS 库,使得你可以借助 MVVM 模式动态生成和更新 css,从 js 事件和 css 选择器的苦海中脱离出来

    dynamic-css 使得你可以借助 MVVM 模式动态生成和更新 css,从而将本插件到来之前,打散.嵌套在 js 中的修改样式的代码剥离出来.比如你要做元素跟随鼠标移动,或者根据滚动条位置的变化 ...

随机推荐

  1. 笛卡尔积算法的sku

    1.笛卡尔积在形式上比较容易理解,但作为按钮操作DOM的时候,我的思路大体还可以,有些偏差.看到这种矩行方阵,首先联想到二维数组,事实上这种方法完全可以实现,但是在性能和编码速度上都有弊端. 2.以下 ...

  2. PHP 运行相关概念

    web server.cgi.cgi程序.fast-cgi.php-fpm.php-cgi

  3. Kaggle(一):房价预测

    Kaggle(一) 房价预测 (随机森林.岭回归.集成学习)  项目介绍:通过79个解释变量描述爱荷华州艾姆斯的住宅的各个方面,然后通过这些变量训练模型, 来预测房价.   kaggle项目链接:ht ...

  4. Linux errno详解

    1. 错误码 / errno Linux中系统调用的错误都存储于 errno中,errno由操作系统维护,存储就近发生的错误,即下一次的错误码会覆盖掉上一次的错误. PS: 只有当系统调用或者调用li ...

  5. Ionic3 UI组件之 ImageViewer

    组件特性: 轻触图片可全屏查看 手势上下滑动可关闭全屏查看 点击导航箭头可关闭视图 双击查看全图,并可放大 参考地址:https://github.com/Riron/ionic-img-viewer ...

  6. 脚手架(create-react-app)没有eject情况下,使用react-scripts的时候,动态设置环境变量

    在实际开发中,例如:有时候打包发布时,需要手动更新版本,比如修改package.json中的version,但是如果有时候忘了修改,那么又得build一次: 如果能动态设置多好,webpack下可以在 ...

  7. Html5音频播放

    Audio标签: 不需要下载任何的额外的浏览器插件 完全由浏览器自身实现音频的解码和播放 用法: <audio src="1.mp3" controls></au ...

  8. C# 之String以及浅拷贝与深拷贝

     一.String到底是值类型还是引用类型 MSDN 中明确指出 String 是引用类型而不是值类型,但 String 表面上用起来却像是值类型,这又是什么原因呢? 首先从下面这个例子入手: //值 ...

  9. Node.js学习笔记(八) --- Node.js的路由模块封装

    1 .模块化的方式封装 整理中… 2 .封装仿照 express 的路由整理中…

  10. 装饰器模式(Decorator Pattern)

    装饰器模式 一.什么是装饰器模式   装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构.这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装 ...