爬虫入门三(bs4模块、遍历文档树、搜索文档树、css选择器)

文章目录

  • 一、bs4模块
  • 二、遍历文档树
  • 三、搜索文档树
  • 四、css选择器

一、bs4模块

beautifulsoup4HTMLXML文件中提取数据的Python库,用它来解析爬取回来的xml。

	1.安装pip install beautifulsoup4 # 下载bs4模块pip install lxml  #解析库2. 用法'第一个参数,是要总的字符串''第二个参数,使用哪个解析库:html.parser(内置的,无需额外安装,速度慢一些)、lxml(需额外安装pip install lxml)'soup=BeautifulSoup('要解析的内容str类型','html.parser/lxml')

二、遍历文档树

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_xx' xx='zz'>lqz <b>The Dormouse's story <span>彭于晏</span></b>  xx</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>
"""if __name__ == '__main__':# soup = BeautifulSoup(html_doc, 'html.parser')soup = BeautifulSoup(html_doc, 'lxml')  # pip install lxml# print(soup.find_all(name='html'))1.文档容错能力res = soup.prettify()print(res)2.遍历文档树:文档树(html开头---->html结尾,中间包含了很多标签)# 通过 .来查找标签 ,且只能找到最先查找到的第一个print(soup.html)print(soup.html.body.p)  # 一层一层的查找到指定的标签print(soup.p)  # 跨层级,直接查找3.获取标签名称print(soup.body.name)4.获取标签的属性p = soup.html.body.pprint(p.attrs)  # 获取p标签的所有属性print(p.attrs['class'])  # 获取指定的一个属性 html类属性可以填写多个所以放在列表中 ['title']print(p.attrs.get('xx'))print(soup.a.attrs['href'])5.获取标签的内容# 标签对象.textprint(soup.p.b.text) # 获取b标签的所有文本# 标签对象.string  使用string指定的标签下,只有自己的文本即可获取,嵌套了标签则为Noneprint(soup.p.b.string)  # None  string不能有子 、孙标签print(soup.p.b.span.string)  # 彭于晏# 标签对象.strings,strings拿到的是一个生成器对象,会把子子孙孙的文本内容都放入生成器中print(soup.p.b.strings) # 和text很像,不过更节约内存print(list(soup.p.b.strings)) #["The Dormouse's story ", '彭于晏']6.嵌套选择print(soup.html.head.title)'''------了解内容------'''7.子节点、子孙节点print(soup.p.contents) # 获取p标签下所有的子节点,只取一个pprint(soup.p.children) # 直接子节点,得到一个迭代器,包含p标签下所有子节点for i,child in enumerate(soup.p.children):  # list_iterator 迭代器print(i,child)print(soup.p.descendants) # 获取子孙节点,p标签下所有的标签都会选择出来for i,child in enumerate(soup.p.descendants): # generator 生成器print(i,child)8.父节点、祖先节点print(soup.a.parent)  # 获取a标签的父节点print(soup.a.parents) # 找到a标签所有的祖先节点 generatorprint(list(soup.a.parents))9.兄弟节点print(soup.a.next_sibling)  # 下一个兄弟标签print(soup.a.previous_sibling) # 上一个兄弟标签print(list(soup.a.next_siblings))  # 下面的兄弟们=>生成器对象print(soup.a.previous_siblings)  # 上面的兄弟们=>生成器对象

三、搜索文档树

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my_p" class="title"><b id="bbb" class="boldest">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>
"""
soup = BeautifulSoup(html_doc,'lxml')
"""五种过滤器: 字符串、正则表达式、列表、True、方法 """
# find:找第一个,find_all:找所有
1.字符串----->查询条件是字符串
res = soup.find(id='my_p')
res=soup.find(class_='boldest')
res=soup.find(href='http://example.com/elsie')
res=soup.find(name='a',href='http://example.com/elsie',id='link1') # 多个and条件
'可以写成下面的,但是里面不能写name'
res = soup.find(attrs={'class':'sister','href':'http://example.com/elsie'})
print(res)2.正则表达式
import re
res = soup.find_all(href=re.compile('^http'))  # href属性以http为开头的所有
res = soup.find_all(class_=re.compile('^s'))  # 所有class中以s为开头的
print(res)3.列表
res = soup.find_all(name=['a','b']) # 拿到所有的a/b标签列表
res = soup.find_all(class_=['sister','boldest']) # 拿到类名为sister、boldest的标签
print(res)4.布尔
res = soup.find_all(id=True) # 拿到所有带有id的标签列表
res = soup.find_all(href=True)  # 所有href属性的标签
res = soup.find_all(class_=True)  # 所有class_属性的标签
print(res)5.方法
def has_class_but_no_id(tag):# 查询所有有id但是没有class的标签return tag.has_attr('class') and not tag.has_attr('id')
print(soup.find_all(has_class_but_no_id))6.搜索文档树可以结合遍历文档树来使用
print(soup.html.body.find_all('p')) # 速度会更快一些,缩小范围查找7.recursive=True   limit=1 limit 参数
print(soup.find_all(name='p',limit=2)) # 只拿前两个p标签 限制拿取条数
print(soup.find_all(name='p',recursive=False)) # 是否递归查找

四、css选择器

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my_p" class="title">asdfasdf<b id="bbb" class="boldest">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>
"""
soup = BeautifulSoup(html_doc,'lxml')
'''select内写css选择器'''
res = soup.select('a.sister')
res = soup.select('#link1')
res = soup.select('p#my_p b')
print(res)'''可以在网页中控制台里面,对应的标签中右键点击Copy selector'''
import requests
header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
res=requests.get('https://www.zdaye.com/free/',headers=header)
# print(res.text)
soup=BeautifulSoup(res.text,'lxml')
res = soup.select('#ipc > tbody > tr:nth-child(2) > td.mtd')
print(res[0].text)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/693447.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

☀️将大华摄像头画面接入Unity 【2】配置Unity接监控画面

一、前言 上一篇咱们将大华摄像头接入到电脑上了&#xff0c;接下来准备接入到unity画面。 接入到监控就涉及到各种视频流的格式rtsp、rtmp、m3u8。 Unity里有一些播放视频流的插件&#xff0c;主要的就是AVPro Video 和 UMP等&#xff0c;这次我用的是UMP 最好使用2.0.3版本…

从0到1的私域流量体系搭建,私域操盘手的底层认知升级

一、教程描述 本套私域操盘手教程&#xff0c;大小4.31G&#xff0c;共有12个文件。 二、教程目录 01第一课、私域能力必修&#xff1a;私域大神熟记于心的高阶私域体系.mp4 02第二课、私域IP打造&#xff1a;那些忍不住靠近的私域IP如何打造的.mp4 03第三课、朋友圈经济&…

论文阅读——SqueezeSAM

SqueezeSAM: User-Friendly Mobile Interactive Segmentation 比SAM更小&#xff0c;更快。 框架&#xff1a; 使用的U型结构 使用BatchNorm而不是LayerNorm节省计算&#xff1b; 对于用户点击和框&#xff0c;单独作为通道&#xff0c;前融合和后融合&#xff08;sam只有后融…

OpenGL学习——16.多光源

前情提要&#xff1a;本文代码源自Github上的学习文档“LearnOpenGL”&#xff0c;我仅在源码的基础上加上中文注释。本文章不以该学习文档做任何商业盈利活动&#xff0c;一切著作权归原作者所有&#xff0c;本文仅供学习交流&#xff0c;如有侵权&#xff0c;请联系我删除。L…

OAuth2.0 最简向导

本文是一篇关于OAuth2.0的启蒙教程&#xff0c;图文并茂&#xff0c;通俗易懂&#xff0c;力求用最简洁明了的方式向初学者解释OAuth2.0是什么。本文并不是冗杂难懂的长篇大论&#xff0c;一图胜千言&#xff0c;深入浅出OAuth2.0&#xff0c;知其然知其所以然。 参考文献 首…

快速上手Spring Boot整合,开发出优雅可靠的Web应用!

SpringBoot 1&#xff0c;SpringBoot简介1.1 SpringBoot快速入门1.1.1 开发步骤1.1.1.1 创建新模块1.1.1.2 创建 Controller1.1.1.3 启动服务器1.1.1.4 进行测试 1.1.2 对比1.1.3 官网构建工程1.1.3.1 进入SpringBoot官网1.1.3.2 选择依赖1.1.3.3 生成工程 1.1.4 SpringBoot工程…

JAVA工程师面试专题-JVM篇

目录 一、运行时数据区 1、说一下JVM的主要组成部分及其作用? 2、说一下 JVM 运行时数据区 ? 3、说一下堆栈的区别 4、成员变量、局部变量、类变量分别存储在什么地方? 5、类常量池、运行时常量池、字符串常量池有什么区别? 6、JVM为什么使用元空间替换永久代 二、…

代码随想录算法训练营29期|day57 任务以及具体安排

第九章 动态规划part14 1143.最长公共子序列 /*二维dp数组 */ class Solution {public int longestCommonSubsequence(String text1, String text2) {// char[] char1 text1.toCharArray();// char[] char2 text2.toCharArray();// 可以在一開始的時候就先把text1, text2 轉成…

week04day01(爬虫)

一. 爬虫 只爬取公开的信息&#xff0c;不能爬取未公开的后台数据 1.爬虫的合法性 法无禁止皆可为 -- 属于法律的灰色地带https://www.tencent.com/robots.txt -- 网站/robots.txt 可以查看禁止爬取的内容 2. URL Uniform Resource Locator 统一资源定位符https://www.…

ACL权限-访问控制列表

一、简介 ACL&#xff08;access control list&#xff09;访问控制列表&#xff0c;可以对单一的用户或者组设置对文件或目录的独立rwx权限。 二、文件系统是否支持ACL权限 ACL权限是传统的Unix-like操作系统权限的额外支持项目&#xff0c;要有文件系统的支持&#xff0c;目前…

Learn HTML in 1 hour

website address https://www.youtube.com/watch?vHD13eq_Pmp8 excerpt All right, what’s going on? everybody. It’s your Bro, hope you’re doing well, and in this video I’m going to help you started with html; so sit back, relax and enjoy the show. If y…

网络爬虫基础(上)

1. 爬虫的基本原理 爬虫就是在网页上爬行的蜘蛛&#xff0c;每爬到一个节点就能够访问该网页的信息&#xff0c;所以又称为网络蜘蛛&#xff1b; 网络爬虫就是自动化从网页上获取信息、提取信息和保存信息的过程&#xff1b; 2. URL的组成部分 URL全称为Uniform Resource L…

linux 创建全局快捷方式

1.查看环境变量 echo $PATH显示结果 /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/nodejs/bin:/home/jetson/ngc-cli 说明:以:为分割符&#xff0c;可以看到一个个文件夹的路径。这些路径就是环境变量。这…

基于Mapbox展示GDAL处理的3D行政区划展示实践

目录 前言 一、Gdal数据处理 1、数据展示 2、Java数据转换 二、Mapbox可视化 1、定义Mapbox地图 2、地图初始化 3、创建地图 三、界面优化 1、区域颜色设置 2、高度自适应和边界区分 3、中文标注 总结 前言 最近有遇到一个需求&#xff0c;用户想在地图上把行政区划…

Android 9.0 禁用插入耳机时弹出的保护听力对话框

1.前言 在9.0的系统rom定制化开发中,在某些产品中会对耳机音量调节过高限制,在调高到最大音量的70%的时候,会弹出音量过高弹出警告,所以产品 开发的需要要求去掉这个音量弹窗警告功能,接下来就来具体实现这个功能 2.禁用插入耳机时弹出的保护听力对话框的核心类 framework…

浅谈ORM框架

文章目录 一、什么是ORM框架&#xff1f;二、常见的ORM框架(持久层框架)2.0 什么是持久化2.1 Hibernate2.1.1、Hibernate的使用步骤 2.2 mybatis2.3 mybatis plus2.4 jpa springdata2.5 jfinal 三、ORM框架的优缺点&#xff1f;3.1 优点3.1.1、减少代码的重复量&#xff0c;提高…

Android 基础技术——Framework

笔者希望做一个系列&#xff0c;整理 Android 基础技术&#xff0c;本章是关于 Framework 简述 Android 系统启动流程 当按电源键触发开机&#xff0c;首先会从 ROM 中预定义的地方加载引导程序 BootLoader 到 RAM 中&#xff0c;并执行 BootLoader 程序启动 Linux Kernel&…

使用Flex布局在HTML中实现双行夹批效果

古代小说中经常有评点和批注&#xff0c;为了区别正文和批注&#xff0c;一般将批注排版成双行夹批的形式。我们知道&#xff0c;在Word中只需要先选择批注文字&#xff0c;然后通过“开始”菜单“段落”面板上字符缩放工具组里的“双行合一”命令&#xff0c;就可以很容易实现…

Android13 针对low memory killer内存调优

引入概念 在旧版本的安卓系统中&#xff0c;当触发lmk&#xff08;low memory killer&#xff09;的时候一般认为就是内存不足导致&#xff0c;但是随着安卓版本的增加lmk的判断标准已经不仅仅是内存剩余大小&#xff0c;io&#xff0c;cpu同样会做评判&#xff0c;从而保证设备…

vue实现列表自动无缝滚动列表

大家好&#xff0c;今天给大家分享的知识是vue基于vue-seamless-scroll实现自动无缝滚动列表 一、实现自动滚动 最近在开发过程中遇到一个问题&#xff0c;就是需要实现自动滚动列表&#xff0c;效果图如下 就是这样一个列表在自动循环展示。在这里我是运用的 vue-seamless-sc…