爬虫入门—BeautifulSoup4的使用

CSS 选择器:BeautifulSoup4

安装:pip install beautifulsoup4
官方文档:http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0

BeautifulSoup 用来解析 HTML 比较简单,API非常人性化,支持CSS选择器、
Python标准库中的HTML解析器,也支持 lxml 的 XML解析器。

使用首先必须要导入 bs4 库

解析器

在这里插入图片描述参考

from bs4 import BeautifulSoup
from bs4 import BeautifulSoup

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 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> 
"""

#创建 Beautiful Soup 对象 
soup = BeautifulSoup(html,'lxml') 
#打开本地 HTML 文件的方式来创建对象 
#soup = BeautifulSoup(open('index.html')) 
#格式化输出 soup 对象的内容 
print(soup.prettify())
四大对象种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

《1》Tag:Tag 通俗点讲就是 HTML 中的一个个标签

《2》NavigableString:字符串常被包含在tag内.Beautiful Soup用NavigableString类来包装tag中的字符串:通过string来获得。

《3》BeautifulSoup:BeautifulSoup 对象表示的是一个文档的内容。大部分时候,可以把它当作 Tag 对象,
是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性

《4》Comment:Comment 对象是一个特殊类型的 NavigableString 对象,其输出的内容不包括注释符号。

选择器

这就是另一种与 find_all 方法有异曲同工之妙的查找方法.写 CSS 时,标签名不加任何修饰,类名前加.,id名前加#在这里我们也可以利用类似的方法来筛选元素,用到的方法是soup.select(),返回类型是 list
在这里插入图片描述
1)通过标签名查找

soup.select('title') 
soup.select('b')

2)通过类名查找

print soup.select('.sister')

3)通过 id 名查找

print soup.select('#link1')

4)组合查找

print soup.select('p #link1')

5)属性查找

print(soup.select('a[class="sister"]'))
soup.select('a[href="http://example.com/elsie"]')
  1. 获取内容
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()) 
	print (title.attrs['class'])
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值