爬虫入门—BeautifulSoup4的使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/LXJRQJ/article/details/100705172

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'])

猜你喜欢

转载自blog.csdn.net/LXJRQJ/article/details/100705172