python_基于bs4html内容遍历

标签树的下行遍历

.contents(内容)         子节点的列表,将<tag>所有的儿子节点存入列表

.childern(孩子)          子节点的迭代类型,与.contents类似,用于循环遍历儿子节点

.descendants (后裔)子孙节点的迭代类型,包含所有子孙节点,用于循环遍历

from bs4 import BeautifulSoup
import requests
try:
    r=requests.get("http://python123.io/ws/demo.html",timeout=30)
    r.raise_for_status()
    r.encoding=r.apparent_encoding
    demo=r.text
    soup=BeautifulSoup(demo,'html.parser')
    print('head标签',soup.head)#<head><title>This is a python demo page</title></head>
    #head内容
    print('head标签的内容',soup.head.contents)
    print('body标签的内容',soup.body.contents)
    #遍历子节点
    for child in soup.body.children:
        print(child)
    #遍历子孙节点
    for descendants in soup.body.descendants:
        print('子孙节点',descendants)
except:
    print("有点问题")

标签树的上行遍历

.parent 节点的父亲标签

.parents 节点先辈标签的迭代类型,用于循环遍历先辈节点

from bs4 import BeautifulSoup
import requests
try:
    #接收响应
    r=requests.get("http://python123.io/ws/demo.html",timeout=30)
    #异常
    r.raise_for_status()
    #编码
    r.encoding=r.apparent_encoding
    #接收返回的html 用BeautifulSoup 进行处理
    demo=r.text
    soup=BeautifulSoup(demo,'html.parser')
    print(soup)
    #打印 标签树的上行遍历
    for parent in soup.a.parents:
        if parent is None :
            print(parent)
        else:
            print('a',parent.name)
except:
    print('异常')

标签树的平行遍历(平行遍历发生在同一节点下):

.next_sibling           返回按照html文本顺序的下一个平行节点标签

.previous_sibling    返回按照HTML文本顺序的上一个平行节点标签

.next_siblings          迭代类型,返回按照HTML 文本顺序的后续所有平行节点标签

.previous_siblings  迭代类型,返回按照HTML文本顺序的前续所有平行节点标签




Python使用BeautifulSoup库(通常简称为bs4)解析HTML,可以按照以下步骤进行操作: 1. 安装BeautifulSoup库:使用pip命令安装bs4库,可以在命令行执行以下命令: ``` pip install bs4 ``` 2. 导入BeautifulSoup库:在Python脚本的开头添加以下代码: ```python from bs4 import BeautifulSoup ``` 3. 读取HTML文件或字符串:有两种方式可以读取HTML内容,你可以选择其之一: - 从本地文件读取HTML内容: ```python with open('example.html', 'r') as f: html_content = f.read() ``` - 直接使用HTML字符串: ```python html_content = """ <html> <head> <title>Example</title> </head> <body> <h1>Hello, world!</h1> </body> </html> """ ``` 4. 创建BeautifulSoup对象:使用BeautifulSoup类将HTML内容解析为BeautifulSoup对象: ```python soup = BeautifulSoup(html_content, 'html.parser') ``` 5. 使用BeautifulSoup对象进行解析:通过BeautifulSoup对象可以获取HTML的各种元素、标签、属性等信息。以下是几个常用的操作示例: - 查找元素: ```python # 根据标签名查找第一个匹配的元素 element = soup.find('div') # 根据标签名查找所有匹配的元素 elements = soup.find_all('a') # 根据CSS选择器查找元素 elements = soup.select('.class-name') ``` - 获取元素内容: ```python # 获取元素的文本内容 text = element.text # 获取元素的属性值 attr_value = element['attribute'] ``` - 遍历元素: ```python # 遍历所有匹配的元素 for element in elements: print(element.text) ``` 这些是使用BeautifulSoup库解析HTML的基本步骤和操作示例。你可以根据具体的需求进行更多的操作,可以参考BeautifulSoup官方文档获取更多用法和示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值