分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

爬虫之BeautifulSoup, CSS

发布时间:2023-09-06 01:07责任编辑:傅花花关键词:CSS爬虫

1. Beautiful Soup的简介

2. Beautiful Soup 安装

可以利用 pip 或者 easy_install 来安装,以下两种方法均可

easy_installbeautifulsoup4

pipinstallbeautifulsoup4
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。
Python标准库:BeautifulSoup(markup, “html.parser”)
lxml HTML 解析器:BeautifulSoup(markup, “lxml”)

4.创建 Beautiful Soup 对象

首先必须要导入 bs4 库:frombs4importBeautifulSoup

我们创建一个字符串,后面的例子我们便会用它来演示

html="""
<html><head><title>The Dormouse‘s story</title></head>
<body>
<p name="dromouse"><b>The Dormouse‘s story</b></p>
<p >Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" ><!-- Elsie --></a>,
<a href="http://example.com/lacie" >Lacie</a> and
<a href="http://example.com/tillie" >Tillie</a>;
and they lived at the bottom of a well.</p>
<p >...</p>
创建 beautifulsoup 对象:soup=BeautifulSoup(html)

另外,我们还可以用本地 HTML 文件来创建对象,例如soup=BeautifulSoup(open(‘index.html‘))

上面这句代码便是将本地 index.html 文件打开,用它来创建 soup 对象

下面我们来打印一下 soup 对象的内容,格式化输出 :printsoup.prettify()

5.四大对象种类

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

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

Tag 是什么?通俗点讲就是 HTML 中的一个个标签,例如:<title>TheDormouse‘sstory</title> ;<ahref="http://example.com/elsie">Elsie</a>

上面的 title a 等等 HTML 标签加上里面包括的内容就是 Tag,下面我们来感受一下怎样用 Beautiful Soup 来方便地获取 Tags

对于 Tag,它有两个重要的属性,是name 和 attrs,下面我们分别来感受一下

printsoup.name
printsoup.head.name
#[document]
#head
printsoup.p.attrs
#{‘class‘: [‘title‘], ‘name‘: ‘dromouse‘}

在这里,我们把 p 标签的所有属性打印输出了出来,得到的类型是一个字典。

如果我们想要单独获取某个属性,可以这样,例如我们获取它的 class 叫什么

printsoup.p[‘class‘]

#[‘title‘]

(2)NavigableString

既然我们已经得到了标签的内容,那么问题来了,我们要想获取标签内部的文字怎么办呢?很简单,用 .string 即可,例如:

printsoup.p.string

#The Dormouse‘s story

(3)BeautifulSoup

BeautifulSoup对象表示的是一个文档的全部内容.大部分时候,可以把它当作Tag对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下

printtype(soup.name)

#<type ‘unicode‘>
printsoup.name
# [document]
printsoup.attrs
#{} 空字典

(4)Comment

Comment对象是一个特殊类型的NavigableString对象,其实输出的内容仍然不包括注释符号,但是如果不好好处理它,可能会对我们的文本处理造成意想不到的麻烦。

我们找一个带注释的标签:

printsoup.a

printsoup.a.string
printtype(soup.a.string)
结果为:
<ahref="http://example.com/elsie"><!--Elsie--></a>
Elsie
<class‘bs4.element.Comment‘>
a 标签里的内容实际上是注释,但是如果我们利用 .string 来输出它的内容,我们发现它已经把注释符号去掉了,所以这可能会给我们带来不必要的麻烦。

7.搜索文档树

(1)find_all( name , attrs , recursive , text , **kwargs )

(2)find( name , attrs , recursive , text , **kwargs )

它与 find_all() 方法唯一的区别是find_all()方法的返回结果是值包含一个元素的列表,而find()方法直接返回结果

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>]
printsoup.find_all(‘a‘)
#[<a href="http://example.com/elsie" ><!-- Elsie --></a>, <a href="http://example.com/lacie" >Lacie</a>, <a href="http://example.com/tillie" >Tillie</a>]

B.传正则表达式

如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的match()来匹配内容.下面例子中找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到

importre
fortaginsoup.find_all(re.compile("^b")):
print(tag.name)
# body
# b
C.传列表

如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有<a>标签和<b>标签

soup.find_all(["a","b"])
# [<b>The Dormouse‘s story</b>,
#<a href="http://example.com/elsie" >Elsie</a>,
#<a href="http://example.com/lacie" >Lacie</a>,
#<a href="http://example.com/tillie" >Tillie</a>]
D.传 True

True可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点

fortaginsoup.find_all(True):
print(tag.name)
# html
# head
# title
# body
# p
# b
# p
# a
# a
E.传方法

如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数[4],如果这个方法返回True表示当前元素匹配并且被找到,如果不是则反回False

下面方法校验了当前元素,如果包含class属性却不包含id属性,那么将返回True:

defhas_class_but_no_id(tag):
returntag.has_attr(‘class‘)andnottag.has_attr(‘id‘)
将这个方法作为参数传入find_all()方法,将得到所有<p>标签:
soup.find_all(has_class_but_no_id)
# [<p ><b>The Dormouse‘s story</b></p>,
#<p >Once upon a time there were...</p>,
#<p >...</p>]
2)keyword 参数
注意:如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为id的参数,Beautiful Soup会搜索每个tag的”id”属性
soup.find_all(id=‘link2‘)
# [<a href="http://example.com/lacie" >Lacie</a>]
如果传入href参数,Beautiful Soup会搜索每个tag的”href”属性
soup.find_all(href=re.compile("elsie"))
# [<a href="http://example.com/elsie" >Elsie</a>]

使用多个指定名字的参数可以同时过滤tag的多个属性

soup.find_all(href=re.compile("elsie"),id=‘link1‘)
# [<a href="http://example.com/elsie" >three</a>]

在这里我们想用 class 过滤,不过 class 是 python 的关键词,这怎么办?加个下划线就可以

soup.find_all("a",class_="sister")
# [<a href="http://example.com/elsie" >Elsie</a>,
#<a href="http://example.com/lacie" >Lacie</a>,
#<a href="http://example.com/tillie" >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

但是可以通过find_all()方法的attrs参数定义一个字典参数来搜索包含特殊属性的tag

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"

4)limit 参数

find_all()方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用limit参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到limit的限制时,就停止搜索返回结果.

文档树中有3个tag符合搜索条件,但结果只返回了2个,因为我们限制了返回数量

soup.find_all("a",limit=2)
# [<a href="http://example.com/elsie" >Elsie</a>,
#<a href="http://example.com/lacie" >Lacie</a>]

5)recursive 参数

调用tag的find_all()方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数recursive=False.

一段简单的文档:

<html>
<head>
<title>
TheDormouse‘sstory
</title>
</head>
...
是否使用recursive参数的搜索结果:
soup.html.find_all("title")
# [<title>The Dormouse‘s story</title>]
soup.html.find_all("title",recursive=False)
# []

8.CSS选择器

我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是soup.select(),返回类型是list

(1)通过标签名查找

printsoup.select(‘title‘)

#[<title>The Dormouse‘s story</title>]

printsoup.select(‘a‘)
#[<a href="http://example.com/elsie" ><!-- Elsie --></a>, <a href="http://example.com/lacie" >Lacie</a>, <a href="http://example.com/tillie" >Tillie</a>]
printsoup.select(‘b‘)
#[<b>The Dormouse‘s story</b>]

(2)通过类名查找

printsoup.select(‘.sister‘)

#[<a href="http://example.com/elsie" ><!-- Elsie --></a>, <a href="http://example.com/lacie" >Lacie</a>, <a href="http://example.com/tillie" >Tillie</a>]
(3)通过 id 名查找
printsoup.select(‘#link1‘)
#[<a href="http://example.com/elsie" ><!-- Elsie --></a>]
(4)组合查找

组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开

printsoup.select(‘p #link1‘)
#[<a href="http://example.com/elsie" ><!-- Elsie --></a>]

直接子标签查找

printsoup.select("head > title")
#[<title>The Dormouse‘s story</title>]

(5)属性查找

查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。

printsoup.select(‘a[]‘)
#[<a href="http://example.com/elsie" ><!-- Elsie --></a>, <a href="http://example.com/lacie" >Lacie</a>, <a href="http://example.com/tillie" >Tillie</a>]
printsoup.select(‘a[href="http://example.com/elsie"]‘)
#[<a href="http://example.com/elsie" ><!-- Elsie --></a>]

同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格

printsoup.select(‘p a[href="http://example.com/elsie"]‘)
#[<a href="http://example.com/elsie" ><!-- Elsie --></a>]
以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text()方法来获取它的内容。
soup=BeautifulSoup(html,‘lxml‘)
printtype(soup.select(‘title‘))
printsoup.select(‘title‘)[0].get_text()
fortitleinsoup.select(‘title‘):
printtitle.get_text()

爬虫之BeautifulSoup, CSS

原文地址:http://www.cnblogs.com/li-20151130/p/7455037.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved