11-python爬虫之Beautiful Soup_beautiful soup 支持xpath吗

CSS Selector

CSS(即层叠样式表Cascading Stylesheet),

Selector来定位(locate)页面上的元素(Elements)。Selenium官网的Document里极力推荐使用CSS locator,而不是XPath来定位元素,原因是CSS locator比XPath locator速度快.

Beautiful Soup
  • 支持从HTML或XML文件中提取数据的Python库
  • 支持Python标准库中的HTML解析器
  • 还支持一些第三方的解析器lxml, 使用的是 Xpath 语法,推荐安装。

Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了

  • Beautiful Soup4 安装

官方文档链接:

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

可以利用 pip来安装

 
  1. pip install beautifulsoup4
  • 安装解析器(上节课已经安装过)
pip install lxml
  • Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .根据操作系统不同,可以选择下列方法来安装lxml:

另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:

 
pip install html5lib

下表列出了主要的解析器:

解析器使用方法优势劣势
Python标准库BeautifulSoup(markup, “html.parser”)Python的内置标准库;执行速度适中;文档容错能力强Python 2.7.3 or 3.2.2前 的版本中文档容错能力差
lxml HTML 解析器BeautifulSoup(markup, “lxml”)速度快;文档容错能力强 ;需要安装C语言库
lxml XML 解析器BeautifulSoup(markup, [“lxml-xml”]) BeautifulSoup(markup, “xml”)速度快;唯一支持XML的解析器需要安装C语言库
html5libBeautifulSoup(markup, “html5lib”)最好的容错性;以浏览器的方式解析文档;生成HTML5格式的文档速度慢;不依赖外部扩展

推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib**, 因为那些Python版本的标准库中内置的HTML解析方法不够稳定.**

  • 快速开始
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>

"""

使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象**,并能按照标准的缩进格式的结构输出:**

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc,'lxml')

下面我们来打印一下 soup 对象的内容

print (soup)

格式化输出soup 对象

print(soup.prettify())

CSS选择器

在写 CSS 时:

标签名不加任何修饰


类名前加点


id名前加 #

利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list

  • 通过标签名查找
print (soup.select('title') )
#[<title>The Dormouse's story</title>]
​
print (soup.select('a'))
#[<a class="sister" href="http://example.com/elsie" id="link1"></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
​
print (soup.select('b'))
#[<b>The Dormouse's story</b>]

  • 通过类名查找
 print (soup.select('.sister'))
#[<a class="sister" href="http://example.com/elsie" id="link1"></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
  • 通过 id 名查找
print(soup.select('#link1'))

# [<a class="sister" href="http://example.com/elsie" id="link1"></a>]

  • 直接子标签查找
print (soup.select("head > title"))

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

  • 组合查找

组合查找即标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,

属性和标签不属于同一节点 二者需要用空格分开

 
print (soup.select('p #link1'))

#[<a class="sister" href="http://example.com/elsie" id="link1"></a>]
  • 属性查找

查找时还可以加入属性元素,属性需要用中括号括起来

注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到

 
print (soup.select('a[class="sister"]'))

#[<a class="sister" href="http://example.com/elsie" id="link1"></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]


print (soup.select('a[href="http://example.com/elsie"]'))

#[<a class="sister" href="http://example.com/elsie" id="link1"></a>]

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

print (soup.select('p a[href="http://example.com/elsie"]'))

#[<a class="sister" href="http://example.com/elsie" id="link1"></a>]

以上的 select 方法返回的结果都是列表形式,可以遍历形式输出

用 get_text() 方法来获取它的内容。

print soup.select('title')[0].get_text()


for title in soup.select('title'):

print (title.get_text())
Tag

Tag 是什么?通俗点讲就是 HTML 中的一个个标签,例如

 
    <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>


    print type(soup.select('a')[0])

输出:

 
bs4.element.Tag

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

  • name
print (soup.name)

print (soup.select('a')[0].name)

输出:

[document]

'a'

soup 对象本身比较特殊,它的 name 即为 [document],对于其他内部标签,输出的值便为标签本身的名称。

  • attrs
print (soup.select('a')[0].attrs)

输出:

 
{'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}

在这里,我们把 soup.select(‘a’)[0] 标签的所有属性打印输出了出来,得到的类型是一个字典。

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

 
print (soup.select('a')[0].attrs['class'])

输出:

['sister']
实战
爬取豆瓣电影排行榜案例

https://movie.douban.com/chart


from bs4 import BeautifulSoup
import urllib.parse
import urllib.request
​
url='https://movie.douban.com/chart'
# 豆瓣排行榜
​
herders={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36', 'Referer':'https://movie.douban.com/','Connection':'keep-alive'}
# 请求头信息
​
req = urllib.request.Request(url,headers=herders)
# 设置请求头
response=urllib.request.urlopen(req)
# response 是返回响应的数据
htmlText=response.read()
# 读取响应数据
​
​
# 把字符串解析为html文档
html = BeautifulSoup(htmlText,'lxml')
​
result = html.select(".pl2")
​
file = open('data.txt','a',encoding='utf-8')
# 打开一个文本文件
​
# 遍历几个
for item in result:
    str = ''
    #声明一个空的字符串
    str += item.select('a')[0].get_text().replace(' ','').replace("\n","")
    # 获取标题文字.替换掉空格.替换掉换行
    str += '('
    # 给评分加个左括号
    str += item.select('.rating_nums')[0].get_text()
    # 获取评分
    str += ')\n'
    # 给评分加个右括号
    print(str)
    # 在控制台输出内容
    file.write(str)
    # 写入文件
​
​
file.close()
# 关闭文件

结果

从邪恶中拯救我/魔鬼对决(台)/请救我于邪恶(7.2)神弃之地/恶魔每时每刻(6.9)监视资本主义:智能陷阱/社交困境/智能社会:进退两难(台)(8.6)我想结束这一切/i’mthinkingofendingthings(风格化标题)(7.3)禁锢之地/Imprisonment/TheTrapped(4.4)鸣鸟不飞:乌云密布/SaezuruToriWaHabatakanai:TheCloudsGather(8.3)树上有个好地方/TheHomeintheTree(7.9)辣手保姆2:女王蜂/撒旦保姆:血腥女王/TheBabysitter2(5.7)冻结的希望/雪藏希望:待日重生/HopeFrozen:AQuestToLiveTwice(8.1)铁雨2:首脑峰会/铁雨2:首脑会谈/钢铁雨2:核战危机(港)(5.8)​

单词表

"""
单词表
Beautiful       美丽的
Soup            汤
url             统一资源定位器
lib             library 库
parse           解析
request         解析
respone         响应
select          选择
open            打开
encoding        编码
get_text        获取文本
write           写
close           关闭
"""

问题?

好,这就是另一种与 XPath 语法有异曲同工之妙的查找方法,觉得哪种更方便?

IT入门 感谢关注练习地址:www.520mg.com/it 0基础python爬虫系列教程

一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

二、学习软件

工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

三、入门学习视频

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里无偿获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值