爬虫03--bs4解析库
0 bs4常用解析器
# bs4:解析xml格式的模块,从xml中找想要的数据
使用requests返回的数据,可能是json,html,文件----》使用bs4解析html格式
# html是xml的一种, 故bs4可以解析html
# 两种常用解析器
from bs4 import BeautifulSoup
# 1.html.parser python内置
soup=BeautifulSoup(html_doc,'html.parser')
# 2.lxml C语言编写的模块 速度比上面快,但是需要安装lxml模块
soup = BeautifulSoup(html_doc, 'lxml') # 具有容错功能
res=soup.prettify() # 美化 (缩进、闭合和结构化显示)
print(res)
# 以下共用此案例
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_p' xx='xx'>我是帅哥<b>The Dormouse's story <span>xxx</span></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>
"""
soup = BeautifulSoup(html_doc, 'lxml')
1 bs4遍历文档树
# 1.用法 通过 .
body=soup.body # 直接通过soup对象.标签名,找到标签对象
print(type(body)) # 类型:bs4.element.Tag
print(body.p) # 标签对象可以继续往下 .
# 2.获取标签的名称
p=soup.p
print(p.name)
# 3.获取标签的属性 (重点)
p=soup.p
print(p.attrs) # 把p标签所有属性变成字典
print(p.attrs['class']) # class 是列表形式---》因为class有多个
print(p['id']) # 也可以直接 ['属性']
# 获取第一个a标签的href属性
a=soup.html.body.a['href']
print(a)
# 4.获取标签的内容
text string strings stripped_strings contents
# 获取第一个p标签的文本内容
p=soup.p
print(p.text) # 获取p子子孙孙所有的文本内容,拼到一起
print(p.string) # p标签有且只有文本才能取出,如果有子标签,取出空
print(list(p.strings) ) # 把子子孙孙的文本内容放到迭代器中,可以列表转出来
print(list(p.stripped_strings) ) # 把子子孙孙的文本内容放到迭代器中,并去除多余空白字符
print(p.contents) # 列表形式,contents获取子节点 若无子节点,只有文本,则获取文本内容
# 5.嵌套选择
p=soup.html.body.p
print(p)
# 以下了解
# 6.子节点、子孙节点
print(soup.p.contents) # p下所有子节点(不包含孙), 是列表形式
# 若有文本内容,无子节点,则取出文本内容,列表形式
print(list(soup.p.children)) # 得到一个迭代器,包含p下所有子节点
print(list(soup.p.descendants)) # 得到一个迭代器,子子孙
# 7.父节点、祖先节点
print(soup.a.parent) # 获取a标签的父节点
print(list(soup.a.parents)) # 找到a标签所有的祖先节点...
# 8.兄弟节点
print(soup.a.next_sibling) # 下一个兄弟,紧邻的,不一定是标签
print(soup.a.previous_sibling) # 上一个兄弟
print(list(soup.a.next_siblings)) # 下面的兄弟们=>生成器对象
print(list(soup.a.previous_siblings)) # 上面的兄弟们=>生成器对象
2 bs4搜索文档树
# 搜索文档树 速度是比遍历慢一些的
# 五种过滤器: 字符串、正则表达式、列表、True、方法
find:找到的第一个
find_all:找到的所有
# 1.字符串: 属性='字符串形式'
res=soup.find_all(name='body')
res=soup.find(name='body')
res=soup.find(class_='story') # class 是关键字,需要写成class_
res=soup.find(id='link2')
res=soup.find(href='http://example.com/lacie')
# 如果传多个参数,表示并列 and条件
res=soup.find_all(href=True,name='a')
# attrs 参数定义一个字典参数,来搜索包含特殊属性
res=soup.find(attrs={'class':'story'})
print(res)
# 2.正则表达式
import re
# 找出b开头的标签,结果有body和b标签
print(soup.find_all(name=re.compile('^b')))
# 找到所有连接的标签
res=soup.find_all(href=re.compile('^http://'))
# 找以 href 以lie结尾的标签
res=soup.find_all(href=re.compile('.*?lie$'))
res=soup.find_all(id=re.compile('^id'))
print(res)
# 3.列表 或关系
res=soup.find_all(name=['p','a'])
res=soup.find_all(class_=['title','story'])
print(len(res))
# 4.布尔
res=soup.find_all(name=True)
res=soup.find_all(href=True)
res=soup.find_all(src=True)
print(res)
# 5.方法:了解
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
print(soup.find_all(has_class_but_no_id))
# 案例
import requests
res=requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=9&start=12&mrd=0.013926765110156447')
soup=BeautifulSoup(res.text,'lxml')
li_list=soup.find_all(name='li',class_='categoryem')
for li in li_list:
res=li.div.a['href']
print(res)
a_list=soup.find_all(href=True,name='a',class_='vervideo-lilink')
print(a_list)
3 bs4其他用法
官网:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find-parents-find-parent
3.1 参数: recursive与limit
# 遍历和搜索,可以混合用 (内部通过链式调用实现)
res = soup.html.body.find('p')
res = soup.find('p')
print(res)
# 1.recursive: 是否递归查找
res=soup.html.body.find_all(name='p',recursive=False)
print(res)
# 2.limit: 查找多少条
res=soup.find_all('p',limit=2)
print(len(res))
# 链式调用(跟语言没关系)
class Person:
def change_name(self, name):
self.name = name
return self
def change_age(self, age):
self.age = age
return self
def __str__(self):
try:
return '我的名字是:%s,我的年龄是:%s' % (self.name, self.age)
except:
return super().__str__()
p = Person()
p.change_name('egon').change_age(14)
print(p)
3.2 bs4修改文档树
# bs4支持修改文档树---》对爬虫没用,对实际写后台代码有用
例如:自动化运维,通过python代码,修改uwsgi/java的配置文件(.xml格式)
# 主流软件的配置文件方式:
redis、nginx: xx.conf
uwsgi、java : xx.xml
mysql : xx.ini
: xx.yaml
# 官网:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id40
3.3 其他选择器
所有解析库:通常会有自己的查找方式(bs4默认是find和find_all),还会支持 css选择器 和 xpath选择器(bs4不支持)
####### css选择器:跟前端css查找一样
bs4支持css选择器
# 语法记住:
#id
.类名
标签名 p
标签名>标签名 紧邻的子
标签名 标签名 子子孙孙
# 1.CSS选择器
print(soup.p.select('.sister'))
print(soup.select('.sister span'))
print(soup.select('#link1'))
print(soup.select('#link1 span'))
print(soup.select('#list-2 .element.xxx'))
print(soup.select('#list-2')[0].select('.element')) # 可以一直select,但其实没必要,一条select就可以了
# 2.获取属性
print(soup.select('#list-2 h1')[0].attrs)
# 3.获取内容
print(soup.select('#list-2 h1')[0].get_text())
####### xpath选择器: 在xml中查找文档的语言
bs4不支持xpath选择器
# 终极大招:css,xpath都不会写怎么办,右键复制
# css选择器的复制: 右键-->copy-->copy selector
css #maincontent > div:nth-child(3) > table > tbody > tr:nth-child(44) > td:nth-child(3)
# XPath选择器的复制:右键-->copy-->copy XPath
xpath //*[@id="maincontent"]/div[2]/table/tbody/tr[44]/td[3]
4 bs4总结
1 推荐使用lxml解析库
2 讲了三种选择器:标签选择器,find与find_all,css选择器
1.标签选择器筛选功能弱,但是速度快
2.建议使用find,find_all查询匹配单个结果或者多个结果
3.如果对css选择器非常熟悉建议使用select
3 记住常用的获取属性attrs和文本值text的方法

浙公网安备 33010602011771号