bs4介绍和遍历文档树、搜索文档树、案例:爬美女图片、 bs4其它用法、css选择器

news/2024/7/19 11:17:51 标签: python, 爬虫

bs4介绍和遍历文档树

BeautifulSoup 是一个可以从HTML或XML文件中提取数据的Python库,解析库

需要安装模块:pip install beautifulsoup4

使用

解析库可以使用 lxml,速度快(必须安装) 可以使用python内置的

python"># html_doc爬出的网页text
soup = BeautifulSoup(html_doc, 'html.parser')

重点:遍历文档树

遍历文档树:即直接通过标签名字选择,特点是选择速度快,但如果存在多个相同的标签则只返回第一个

  1. 用法:通过 .遍历
    python"># 拿到 以下的第一个title
    res=soup.html.head.title
    
    # 拿到第一个p
    res=soup.p
    

  2. 取标签的名称
    python">res=soup.html.head.title.name
    res=soup.p.name
    

  3. 获取标签的属性
    python"># 标签的所有属性
    res=soup.body.a.attrs  # 所有属性放到字典中 :{'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}
    
    # 获取第一个属性值
    res=soup.body.a.attrs.get('href')
    res=soup.body.a.attrs['href']
    res=soup.body.a['href']
    

  4. 获取标签的内容
    python">res=soup.body.a.text
    res=soup.p.text
    
    # 这个标签有且只有文本,才取出来,如果有子孙,就是None
    res=soup.a.string  
    res=soup.p.strings
    

  5. 嵌套选择
    就是通过.嵌套

  6. 子节点、子孙节点
    python">#p下所有子节点
    print(soup.p.contents)
    
    #得到一个迭代器,包含p下所有子节点
    print(list(soup.p.children)) 
    
    #获取子子孙节点,p下所有的标签都会选择出来
    print(list(soup.p.descendants)) 
    

  7. 父节点、祖先节点
    python">#获取a标签的父节点
    print(soup.a.parent)
    
    #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...
    print(list(soup.a.parents) )
    

  8. 兄弟节点
    python">print(soup.a.next_sibling) #下一个兄弟
    print(soup.a.previous_sibling) #上一个兄弟
    print(list(soup.a.next_siblings)) #下面的兄弟们=>生成器对象
    print(soup.a.previous_siblings) #上面的兄弟们=>生成器对象
    

搜索文档树

  1. find_all :找所有 列表
  2. find:找一个 Tag类的对象

find和find_all

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

字符串

可以按标签名,可以按属性,可以按文本内容

无论按标签名,按属性,按文本内容 都是按字符串形式查找

python"># 找到类名叫 story的p标签
p=soup.find('p')

# 可以按标签名,可以按属性,可以按文本内容
p=soup.find(name='p',class_='story')
obj=soup.find(name='span',text='lqz')
obj=soup.find(href='http://example.com/tillie')

# 属性可以写成这样
obj=soup.find(attrs={'class':'title'})

正则

无论按标签名,按属性,按文本内容 都是按正则形式查找

python">import re

# 找到所有名字以b开头的所有标签
obj=soup.find_all(name=re.compile('^b'))

# 以y结尾
obj=soup.find_all(name=re.compile('y$'))

obj=soup.find_all(href=re.compile('^http:'))
obj=soup.find_all(text=re.compile('i'))

列表

无论按标签名,按属性,按文本内容 都是按列表形式查找

python"># 所有a标签和标签放到一个列表里
obj=soup.find_all(name=['p','a'])
obj = soup.find_all(class_=['sister', 'title'])

True

无论按标签名,按属性,按文本内容 都是按布尔形式查找

python">obj=soup.find_all(id=True)
obj=soup.find_all(href=True)
obj=soup.find_all(name='img',src=True)

方法

无论按标签名,按属性,按文本内容 都是按方法形式查找

python">## 有class但没有id
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

print(soup.find_all(name=has_class_but_no_id))

案例:爬美女图片

python">import requests
from bs4 import BeautifulSoup

res = requests.get('https://pic.netbian.com/tupian/32518.html')
res.encoding = 'gbk'

soup = BeautifulSoup(res.text, 'html.parser')

ul = soup.find('ul', class_='clearfix')
img_list = ul.find_all(name='img', src=True)

for img in img_list:
    try:
        url = img.attrs.get('src')
        if not url.startwith('http'):
            url = 'https://pic.netbian.com' + url
        res1 = requests.get('url')
        name = url.split('-')[-1]
        with open('./img/%s' % name, 'wb') as f:
            for line in res1.iter_content():
                f.write(line)
    except Exception as e:
        continue

bs4其它用法

  1. 遍历,搜索文档树 ⇢ \dashrightarrow bs4还可以修改xml

    • java的配置文件一般喜欢用xml写
    • .conf
    • .ini
    • .yaml
    • .xml
  2. find_all 其他参数

    • limit=数字 找几条 ,如果写1 ,就是一条
    • recursive:默认是True,如果改False,在查找时只查找子节点标签,不再去子子孙孙中寻找
  3. 搜索文档树和遍历文档树可以混用,找属性,找文本跟之前学的一样

css选择器

  1. id选择器:#id号
  2. 标签选择器:标签名
  3. 类选择器:.类名
  4. 属性选择器
需要记住的
  1. #id
  2. .sister
  3. head
  4. div>a:# div下直接子节点a
  5. div a :div下子子孙孙节点a

一旦会了css选择器的用法 ⇢ \dashrightarrow 以后所有的解析库都可以使用css选择器去找
查找:p=soup.select('css选择器')
复制参考:https://www.runoob.com/cssref/css-selectors.html

案例
python">import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')
soup = BeautifulSoup(res.text, 'html.parser')

# 以后直接复制即可
p = soup.select('a[title="下载哔哩哔哩视频"]')[0].attrs.get('href')
print(p)


http://www.niftyadmin.cn/n/5164555.html

相关文章

数据结构之单链表基本操作

🤷‍♀️🤷‍♀️🤷‍♀️ 今天给大家分享的是单链表的基本操作。 清风的个人主页 🎉欢迎👍点赞✍评论❤️收藏 😛😛😛希望我的文章能对你有所帮助,有不足的地方还请各位…

ubuntu(18.04)中安装open babel docker镜像并在php项目中调用容器中的obabel命令解析结果使用

使用软件: obabel镜像:informaticsmatters/obabel docker:http:// https://www.docker.com/ 安装docker #卸载旧版本sudo apt-get remove docker docker-engine docker-ce docker.io#更新索引包sudo apt-get update#安装 apt 依赖包&…

【应用前沿】360QPaaS 精彩亮相首届中国航空制造设备博览会 | 数智航空

近日,首届“中国航空制造设备博览会”(CAEE2023)在宁波国际会展中心顺利召开,本届大会以“数智产融 开放发展”为主题,以“新技术、新产品、新服务、新企业”为定位,以特色化、专业化、品牌化、高端化为方向…

用户交互引导大模型生成内容特征,LLM-Rec框架助力个性化推荐!

欢迎来到魔法宝库,传递AIGC的前沿知识,做有格调的分享❗ 喜欢的话记得点个关注吧! 今天主要和大家分享一篇使用大语言模型做数据增强来提升推荐系统性能的研究 标题: LLM-Rec: Personalized Recommendation via Prompting Large …

node插件MongoDB(二)——MongoDB的基本命令

文章目录 前言1. 数据库命令(1)显示所有数据库(2)切换指定数据库(若没有自动创建)(3)显示当前所在数据库(4)删除当前数据库 2.集合(表名&#xff…

kafka开启SSL认证(包括内置zookeeper开启SSL)

zookeeper和kafka的SSL开启都可单独进行 生成SSL证书 使用jre自带的keytool工具生成,linux和windows下生成的证书可以通用 生成含有一个私钥的keystore文件,有效期10年(本文证书密码统一使用test123) keytool -genkeypair -ali…

CentOS7安装Xrdp以便Windows远程桌面连接

Centos7已经安装了桌面环境,想要Windows系统远程连接到桌面。 1,which vncserver 如果返回no vncserver,则需要安装 2,yum -y install tigervnc* 3,安装Xrdp yum install epel* -y yum --enablerepoepel -y install xrdp 4…

死亡游戏:密室互猜硬币规则及其破解方法

今天听到一个有点小恐怖的死亡游戏 规则是 将你和最好的朋友 分别关进两个不同的房间 要关 100天 在被关的时间里 你们无法进行任何的沟通 每一天 会有一个人在你和朋友的房间分别抛一次硬币 你们需要去猜对方硬币的正反面 只需要一个人猜对了 则 相安无事 如果两个人都猜错了…