BeautifulSoup学习笔记6

本文档介绍了BeautifulSoup库中CSS选择器的使用,包括按标签、类、ID和属性查找元素,以及查找子标签和同级元素。此外,还探讨了如何利用unwrap()和extract()方法修改文档树,以及输出格式如prettify()、非美化打印、get_text()等。
摘要由CSDN通过智能技术生成

上几篇笔记记录了BeautifulSoup对文档的搜索功能。
find_all()方法,加上合适的过滤器,几乎能满足网页爬虫的需要。

这篇文章先把搜索文档最后的CSS选择器讲完,然后简单地介绍修改文档树和最后的结果输出。
下篇文章详细介绍bs4编码和输出格式。
bs4文档就看完了。

1 CSS selectors

Beautiful Soup supports the most commonly-used CSS selectors. Just pass a string into the .select() method of a Tag object or the BeautifulSoup object itself.

这里有一篇文章:CSS 选择器参考手册http://www.w3school.com.cn/cssref/css_selectors.asp
下面用到的语法都能在这篇文章中找到。

接着用爱丽丝文档作为例子:

>>> 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>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html_doc,"html.parser")

1.1 find tags

>>> soup.select('p')
[<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 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 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值