关键词搜索

源码搜索 ×
×

11-python爬虫之Beautiful Soup

发布2021-09-27浏览351次

详情内容

辅助视频教程:Python基础教程|xin3721自学网icon-default.png?t=L892https://www.xin3721.com/eschool/pythonxin3721/

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 安装

    官方文档链接:

Beautiful Soup Documentation — Beautiful Soup 4.9.0 documentation

可以利用 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解析方法不够稳定.

  • 快速开始
  1. html_doc ="""
  2. <html><head><title>The Dormouse's story</title></head>
  3. <body>
  4. <p class="title"><b>The Dormouse's story</b></p>
  5. <p class="story">Once upon a time there were three little sisters; and their names were
  6. <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
  7. <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
  8. <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  9. and they lived at the bottom of a well.</p>
  10. <p class="story">...</p>
  11. """

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

from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,'lxml')

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

print (soup)

格式化输出soup 对象

print(soup.prettify())

image

CSS选择器

在写 CSS 时:

标签名不加任何修饰  类名前加点  id名前加 #

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

  • 通过标签名查找
  1. print (soup.select('title') )
  2. #[<title>The Dormouse's story</title>]
  3. print (soup.select('a'))
  4. #[<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>]
  5. print (soup.select('b'))
  6. #[<b>The Dormouse's story</b>]
  • 通过类名查找
  1. print (soup.select('.sister'))
  2. # [<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 名查找
  1. print(soup.select('#link1'))
  2. # [<a class="sister" href="http://example.com/elsie" id="link1"></a>]
  • 直接子标签查找
  1. print (soup.select("head > title"))
  2. #[<title>The Dormouse's story</title>]
  • 组合查找

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

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

  1. print (soup.select('p #link1'))
  2. #[<a class="sister" href="http://example.com/elsie" id="link1"></a>]
  • 属性查找

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

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

  1. print (soup.select('a[class="sister"]'))
  2. #[<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>]
  3. print (soup.select('a[href="http://example.com/elsie"]'))
  4. #[<a class="sister" href="http://example.com/elsie" id="link1"></a>]

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

  1. print (soup.select('p a[href="http://example.com/elsie"]'))
  2. #[<a class="sister" href="http://example.com/elsie" id="link1"></a>]

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

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

  1. print(soup.select('title')[0].get_text() )
  2. for title in soup.select('title'):
  3. print (title.get_text())

Tag

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

  1. <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
  2. 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']

实战

爬取豆瓣电影排行榜案例

豆瓣电影排行榜

image

  1. from bs4 import BeautifulSoup
  2. import urllib.parse
  3. import urllib.request
  4. url='https://movie.douban.com/chart'
  5. # 豆瓣排行榜
  6. 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'}
  7. # 请求头信息
  8. req = urllib.request.Request(url,headers=herders)
  9. # 设置请求头
  10. response=urllib.request.urlopen(req)
  11. # response 是返回响应的数据
  12. htmlText=response.read()
  13. # 读取响应数据
  14. # 把字符串解析为html文档
  15. html = BeautifulSoup(htmlText,'lxml')
  16. result = html.select(".pl2")
  17. file = open('data.txt','a',encoding='utf-8')
  18. # 打开一个文本文件
  19. # 遍历几个
  20. for item in result:
  21. str = ''
  22. #声明一个空的字符串
  23. str += item.select('a')[0].get_text().replace(' ','').replace("\n","")
  24. # 获取标题文字.替换掉空格.替换掉换行
  25. str += '('
  26. # 给评分加个左括号
  27. str += item.select('.rating_nums')[0].get_text()
  28. # 获取评分
  29. str += ')\n'
  30. # 给评分加个右括号
  31. print(str)
  32. # 在控制台输出内容
  33. file.write(str)
  34. # 写入文件
  35. file.close()
  36. # 关闭文件

结果

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

单词表

  1. """
  2. 单词表
  3. Beautiful 美丽的
  4. Soup 汤
  5. url 统一资源定位器
  6. lib library 库
  7. parse 解析
  8. request 解析
  9. respone 响应
  10. select 选择
  11. open 打开
  12. encoding 编码
  13. get_text 获取文本
  14. write 写
  15. close 关闭

问题?

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

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载