乐趣区

关于python:11python爬虫之Beautiful-Soup

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/softwa…

能够利用 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 语言库
html5lib BeautifulSoup(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)

![
](https://upload-images.jianshu…

格式化输入 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

退出移动版