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

2024-02-21 08:20

本文主要是介绍爬虫入门三(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)

这篇关于爬虫入门三(bs4模块、遍历文档树、搜索文档树、css选择器)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/731124

相关文章

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

【 html+css 绚丽Loading 】000046 三才归元阵

前言:哈喽,大家好,今天给大家分享html+css 绚丽Loading!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 📚一、效果📚二、信息💡1.简介:💡2.外观描述:💡3.使用方式:💡4.战斗方式:💡5.提升:💡6.传说: 📚三、源代码,上代码,可以直接复制使用🎥效果🗂️目录✍️

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

认识、理解、分类——acm之搜索

普通搜索方法有两种:1、广度优先搜索;2、深度优先搜索; 更多搜索方法: 3、双向广度优先搜索; 4、启发式搜索(包括A*算法等); 搜索通常会用到的知识点:状态压缩(位压缩,利用hash思想压缩)。

hdu1240、hdu1253(三维搜索题)

1、从后往前输入,(x,y,z); 2、从下往上输入,(y , z, x); 3、从左往右输入,(z,x,y); hdu1240代码如下: #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#inc

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来