bs4获取html中body中的所有子标签

html = """<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>科创板落地时间轴预测</title>
  <link rel="stylesheet" href="https://stackedit.io/style.css" />
</head>

<body class="stackedit">
  <div class="stackedit__html"><h2><a id="_0"></a><strong>科创板落地时间轴预测
  </strong></h2>
<p><strong>2019年3月2日</strong></p>
<blockquote>
<p>中国证监会正式发布《科创板首次公开发行股票注册管理办(试行)》和《科创板上市公司持续监管
办法(试行)》,自公布之日起实施。经证监会批准,上交所、中国结算相关业务规则随之发布</p>
</blockquote>
<p><strong>2019年3月18日</strong></p>
<blockquote>
<p>上市审核系统正式对外受理科创板项目申报</p>
</blockquote>
<p><strong>2019年6月中旬(预计最快时间)</strong></p>
<blockquote>
<p>第一批申报科创板的企业通过审核,科创板开板<br>
预期2019全年的科创板上市企业或在150家左右,预估募资规模500-1000亿元</p>
</blockquote>
<p><strong>2020年</strong></p>
<blockquote>
<p>2020年阶段性成熟成果可期<br>
未来科创板有望吸引体量更大的海外中概股或独角兽企业上市</p>
</blockquote>
</div>
</body>

</html>
"""
from bs4 import BeautifulSoup


# 2.读取HTML字符串
soup = BeautifulSoup(html, 'html.parser')

a = soup.body.descendants
# print(list(a))
res = ''
for i in a:
    if str(i).strip():
        print('+++', i)
        res = i
        break
    print('\n\n\n')

print('++', res, '++')


在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、付费专栏及课程。

余额充值