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来装置
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)
)
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 BeautifulSoupimport urllib.parseimport urllib.requesturl='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