【工具】类html 字符串转换成html 进行数据解析

【lxml】

【方案一】 使用lxml 库进行解析 ,目前使用

复制代码
 1 from lxml import html
 2 
 3 # 假设这是你的HTML内容
 4 html_content = """
 5 <html>
 6   <head><title>Example</title></head>
 7   <body>
 8     <div id="content">
 9       <h1>Hello, World!</h1>
10       <p class="description">This is a simple example.</p>
11     </div>
12   </body>
13 </html>
14 """
15 
16 # 解析HTML内容
17 tree = html.fromstring(html_content)
18 
19 # 使用XPath定位元素
20 title = tree.xpath('//title/text()')[0]
21 h1_text = tree.xpath('//h1/text()')[0]
22 description = tree.xpath('//p[@class="description"]/text()')[0]

result = tree.xpath('//select[@id="setting_gps_mode"]/option[1]/@value' # 获取value 值
23 
24 print(f"Title: {title}")
25 print(f"H1 Text: {h1_text}")
26 print(f"Description: {description}")
复制代码

【方案二】使用 BeautifulSoup

BeautifulSoup 是一个用于解析HTML和XML文档的库,它创建了一个解析树,从中可以提取和操纵数据。虽然BeautifulSoup本身不支持XPath,但它支持CSS选择器,这在很多情况下也是足够强大的。

复制代码
 1 from bs4 import BeautifulSoup
 2 
 3 # 假设这是你的HTML内容
 4 html_content = """
 5 <html>
 6   <head><title>Example</title></head>
 7   <body>
 8     <div id="content">
 9       <h1>Hello, World!</h1>
10       <p class="description">This is a simple example.</p>
11     </div>
12   </body>
13 </html>
14 """
15 
16 # 解析HTML内容
17 soup = BeautifulSoup(html_content, 'html.parser')
18 
19 # 使用CSS选择器定位元素
20 title = soup.title.string
21 h1_text = soup.h1.string
22 description = soup.select_one('p.description').text
23 
24 print(f"Title: {title}")
25 print(f"H1 Text: {h1_text}")
26 print(f"Description: {description}")
复制代码

 

posted on   张凌赫_帅  阅读(56)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示