解析库bs4的使用

这篇具有很好参考价值的文章主要介绍了解析库bs4的使用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、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复制即可~~
示例:文章来源地址https://www.toymoban.com/news/detail-520082.html

# 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]

到了这里,关于解析库bs4的使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Python爬虫之Requests库、BS4解析库的下载和安装

    一、Requests库下载地址 requests · PyPI 将下载的.whl文件放在Script目录下  win+r 输入cmd 进入windows控制台 进入到Scripts目录 输入pip3.10 install requests-2.28.1-py3-none-any.whl(文件的名称) 出现Successful install即安装成功  二、BS4解析库的下载和安装 进入到scripts目录 pip install bs4 由于 BS4

    2024年02月05日
    浏览(30)
  • 解析库bs4的使用

    安装: pip3 install Beautifulsoup4 1.bs4遍历文档树 bs4:解析xml格式的模块,从xml中找想要的数据。 html是xml的一种,解析html,使用requests返回的数据,可能是json、html、文件,再使用bs4解析html格式。 用法: 注:lxml比html.parser速度块,但是需要安装lxml模块( pip3 install lxml ) 2.bs4搜

    2024年02月12日
    浏览(30)
  • python-网络爬虫.BS4

    BS4 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库, 它能够通过你喜欢的转换器实现惯用的文档导航、查找、修改文档的方 式。 Beautiful Soup 4 官方文档: https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/ 帮助手册: https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/ 一、安装Beaut

    2024年02月14日
    浏览(22)
  • python爬虫8:bs4库

    前言 ​ python实现网络爬虫非常简单,只需要掌握一定的基础知识和一定的库使用技巧即可。本系列目标旨在梳理相关知识点,方便以后复习。 申明 ​ 本系列所涉及的代码仅用于个人研究与讨论,并不会对网站产生不好影响。 目录结构 1. 概述与安装 ​ bs4是BeautifulSoup4的简

    2024年02月12日
    浏览(23)
  • 【Python爬虫】Python爬虫三大基础模块(urllib & BS4 & Selenium)

    参考资料 Python爬虫教程(从入门到精通) Python urllib | 菜鸟教程 Beautiful Soup 4 入门手册_w3cschool Selenium入门指南 Selenium教程 什么是 Scrapy|极客教程 Scrapy入门教程 1、网络爬虫是什么? 我们所熟悉的一系列 搜索引擎都是大型的网络爬虫 ,比如百度、搜狗、360浏览器、谷歌搜索等

    2024年02月12日
    浏览(32)
  • 【用Vscode实现简单的python爬虫】从安装到配置环境变量到简单爬虫以及python中pip和request,bs4安装

    第一步:安装python包  可以默认,也可以选择自己想要安装的路径 python下载资源链接: Download Python | Python.org 第二步: 配置python环境变量,找到我的电脑-属性-高级-环境变量 找到python,新增 然后将刚刚安装的路径配置到path路径下: 特别注意,配置了环境变量后要进行重启电

    2024年02月15日
    浏览(37)
  • 使用bs4 分析html文件

    首先需要 pip install beautifulsoup4 安装 然后为了方便学习此插件,随便打开一个网页,然后鼠标右键,打开源网页,如下图片 这样就可以获得一个网页源码,全选复制粘贴到本地,存储为 .html 文件,后续的学习以此html文件为模版进行 如,html文件中含结构 我使用如下命令: 例

    2024年01月17日
    浏览(32)
  • Python爬虫解析工具之xpath使用详解

    爬虫抓取到整个页面数据之后,我们需要从中提取出有价值的数据,无用的过滤掉。这个过程称为 数据解析 ,也叫 数据提取 。数据解析的方式有多种,按照 网站数据来源 是静态还是动态进行分类,如下: 动态网站: 字典取值 。动态网站的数据一般都是JS发过来的,基本

    2024年02月12日
    浏览(32)
  • Python爬虫——解析插件xpath的安装及使用

    目录 1.安装xpath 2.安装lxml的库 3.xpath基本语法 4.案例一:获取百度网站的百度一下字样 5.案例二:爬取站长素材网上的前十页照片 打开谷歌浏览器 -- 点击右上角小圆点 -- 更多工具 -- 扩展程序  下载xpath压缩包,下载地址:阿里云盘分享 把压缩包解压到指定目录 -- 选择加

    2024年02月02日
    浏览(29)
  • 尚硅谷爬虫(解析_xpath的基本使用)笔记

    创建一个简单的HTML: 创建一个python文件: 如果解析本地文件使用etree.parse 如果解析服务器响应文件使用etree.HTML() 运行:  会报错 lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: meta line 4 and head, line 6, column 8 原因是 xpath 严格遵守HTML规范   解决方法: 在meta标签中加入 /  再次

    2023年04月21日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包