【工具】类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 2024-12-17 10:06  张凌赫_帅  阅读(137)  评论(0)    收藏  举报

导航