解析库bs4的使用

该文介绍了如何使用Python的BeautifulSoup(bs4)库来解析HTML和XML文档,包括安装、遍历文档树、搜索文档树的方法,如通过标签名、属性、正则表达式等进行查找。同时,文章提到了lxml作为更快的解析器以及如何使用CSS选择器和XPath进行更复杂的查找操作。
摘要由CSDN通过智能技术生成

一、bs4的使用

安装:pip3 install Beautifulsoup4

1.bs4遍历文档树
bs4:解析xml格式的模块,从xml中找想要的数据。
html是xml的一种,解析html,使用requests返回的数据,可能是json、html、文件,再使用bs4解析html格式。

用法:

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, 'html.parser')

# 速度比上面快,但是需要安装lxml模块 pip3 install lxml
soup = BeautifulSoup(html_doc, 'lxml')
res = soup.prettify()  # 美化
print(res)

# ----------遍历文档树----------
# 1、用法  通过 .
body = soup.body  # 直接通过soup对象.标签名,找到标签对象
print(type(body))
print(body.p)
# bs4.element.Tag   标签对象可以继续往下 .

# 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
# 获取第一个p标签的文本内容
p = soup.p
print(p.text) # 获取p子子孙孙所有的文本内容,拼到一起
print(p.string) # p标签有且只有文本才能取出,如果有子标签,取出空
print(list(p.strings))  # 把子子孙孙的文本内容放到迭代器中

# 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)) #上面的兄弟们=>生成器对象

注:lxml比html.parser速度块,但是需要安装lxml模块(pip3 install lxml

2.bs4搜索文档树
搜索文档树速度是比遍历慢一些的。

五种过滤器:
字符串、正则表达式、列表、True、方法

两种方法:
find:找到的第一个 find_all:找到的所有

用法:

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')

# 字符串:指的的 属性='字符串形式'
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(attrs={'class':'story'})
print(res)

# 正则表达式
import re
print(soup.find_all(name=re.compile('^b'))) #找出b开头的标签,结果有body和b标签
# 找到所有所有连接的标签
res=soup.find_all(href=re.compile('^http://'))
res=soup.find_all(href=re.compile('.*?lie$'))
res=soup.find_all(id=re.compile('^id'))
print(res)

# 列表
res=soup.find_all(name=['p','a'])
res=soup.find_all(class_=['title','story'])
print(len(res))

# 布尔
res=soup.find_all(name=True)
res=soup.find_all(href=True)
res=soup.find_all(src=True)  # 把当前页面的图片拿出来
print(res)

# 方法(了解)
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)

li_list=soup.find_all(href=True,name='a',class_='vervideo-lilink')
print(li_list)

3.bs4其他用法
遍历和搜索,可以混合用
recursive :是否递归查找
limit:查找多少条

用法:

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')

# 遍历和搜索,可以混合用
res=soup.html.body.find('p')
res = soup.find('p')
print(res)

# recursive :是否递归查找
res=soup.html.body.find_all(name='p',recursive=False)
print(res)

# limit 查找多少条
res=soup.find_all('p',limit=2)
print(len(res))

补充:
1 链式调用(跟语言没关系)

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)

2 bs4支持修改文档树,对爬虫没用,对实际写后台代码有用

3 主流软件的配置文件方式
xxx.conf(redis,nginx)
xxx.ini(mysql)
xxx.xml(uwsgi,java的配置文件居多)
xxx.yaml

4 css选择器
所有解析库,通常会有自己的查找方式(bs4就是find和find_all),还会支持css和想xpath选择。
记住一些css选择器用法:

id#
类名.
标签名p
标签名>标签名 紧邻的子
标签名 标签名 子子孙孙

res=soup.select('#id_p')
res=soup.select('p>a')
print(res)

5 xpath:在xml中查找文档的语言

6 css、xpath都不会写怎么办
终极大招:浏览器F12选中页面元素,鼠标右击选择xpath或css复制即可~~
示例:

# css 
# maincontent > div:nth-child(3) > table > tbody > tr:nth-child(44) > td:nth-child(3)
# xpath
# //*[@id="maincontent"]/div[2]/table/tbody/tr[44]/td[3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每 天 早 睡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值