Python爬虫基础知识笔记——聚焦爬虫bs4

本文详细介绍了如何使用Python的BeautifulSoup库进行HTML和XML数据解析,包括实例化对象、标签定位、数据提取以及不同方法的选择。从本地文件到网络源码,内容涵盖了关键操作如find(), find_all(), select()和层级选择,还有文本获取、属性获取等技巧。
摘要由CSDN通过智能技术生成

bs4(Python独有)

bs4数据解析的原理:

  • 实例化一个BeautifulSoup对象,并将页面源码数据加载到该对象中
  • 通过调用BeautifulSoup对象相关的属性或者方法进行标签定位和数据提取

环境的安装

在这里插入图片描述
下载lxml的解析器
在这里插入图片描述

实例化BeautifulSoup

1. from bs4 import BeautifulSoup

2. 对象的实例化:

1. 将本地的html文档中的数据加载到该对象中

在这里插入图片描述
在这里插入图片描述

from bs4 import BeautifulSoup
with open('./sogou.html','r',encoding='utf-8') as fp:
    soup=BeautifulSoup(fp,'lxml')
    print(soup)

在这里插入图片描述

2. 将互联网上获取的页面源码加载到该对象中

page_text = response.text
soup = BeautifulSoup(page_text,‘lxml’)

提供的用于数据解析的方法和属性

soup.tagName 返回的是html中第一次出现的tagName标签
from bs4 import BeautifulSoup
with open('./江西理工大学.html','r',encoding='utf-8') as fp:
    soup=BeautifulSoup(fp,'lxml')
    print(soup.a)

在这里插入图片描述

soup.find()
  1. soup.find(‘tagName’)等同于soup.tagName
from bs4 import BeautifulSoup
with open('./江西理工大学.html','r',encoding='utf-8') as fp:
    soup=BeautifulSoup(fp,'lxml')
    print(soup.find('div'))

在这里插入图片描述

soup.find(‘div’)相当于soup.div
2.属性定位

from bs4 import BeautifulSoup
with open('./江西理工大学.html','r',encoding='utf-8') as fp:
    soup=BeautifulSoup(fp,'lxml')
    print(soup.find('div',class_='tab-item'))

在这里插入图片描述

soup.find_all()

可以找到所有符合要求的(列表)

from bs4 import BeautifulSoup
with open('./江西理工大学.html','r',encoding='utf-8') as fp:
    soup=BeautifulSoup(fp,'lxml')
    print(soup.find_all('a'))

在这里插入图片描述

soup.select()
  1. select(‘某种选择器’),返回的是一个列表。
from bs4 import BeautifulSoup
with open('./江西理工大学.html','r',encoding='utf-8') as fp:
    soup=BeautifulSoup(fp,'lxml')
    print(soup.select('.share-pop'))

在这里插入图片描述
2. 层级选择器

from bs4 import BeautifulSoup
with open('./江西理工大学.html','r',encoding='utf-8') as fp:
    soup=BeautifulSoup(fp,'lxml')
    print(soup.select('.share-pop > a')[0])

一个>是一个层级,空格表示的是多个层级
在这里插入图片描述

获取标签之间的文本数据

soup.a.text/string/get_text()
区别:
text/get_text():可以获取某个标签中所有的文本内容
string:只能获取直系的文本内容

获取标签中的属性值

soup.a[‘属性名称’]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值