发布于 2026-01-06 8 阅读
0

HTML 解析器 - 轻松提取 HTML 信息

HTML 解析器 - 轻松提取 HTML 信息

你好,程序员,

本文介绍了一些实用的代码片段,用于使用用 Python / BS4 库编写的HTML 解析器开发工具提取和处理 HTML 信息。

感谢阅读! - 内容由App Generator提供


我们将涵盖以下主题:

  • ✅ 加载 HTML
  • ✅ 扫描文件中的资源:图像、JavaScript 文件、CSS 文件
  • ✅ 更改现有资产的路径
  • ✅ 更新现有元素:更改图像的 src 属性
  • ✅ 根据 ID 定位元素
  • ✅ 从 DOM 树中移除元素
  • ✅ 处理现有组件:删除硬编码文本
  • ✅ 将处理后的 HTML 保存到文件

HTML解析概念

根据维基百科的定义,解析或句法分析是指根据形式语法规则分析一串符号的过程,该符号可以是自然语言或计算机语言。这里所说的HTML解析是指加载HTML代码,提取并处理相关信息,例如标题、页面资源、主要章节等,最后保存处理后的文件。


解析器环境

这段代码使用了BeautifulSoup库,这是一个用 Python 编写的知名解析库。要开始编写代码,我们需要在系统上安装一些模块。

$ pip install ipython # the console where we execute the code
$ pip install requests # a library to pull the entire HTML page
$ pip install BeautifulSoup # the real magic is here 
Enter fullscreen mode Exit fullscreen mode

加载 HTML 内容

该文件将像其他任何文件一样加载,其内容应注入到 BeautifulSoup 对象中。

from bs4 import BeautifulSoup as bs

# Load the HTML content
html_file = open('index.html', 'r')
html_content = html_file.read()
html_file.close() # clean up

# Initialize the BS object
soup  = bs(html_content,'html.parser') 
# At this point, we can interact with the HTML 
# elements stored in memory using all helpers offered by BS library
Enter fullscreen mode Exit fullscreen mode

解析 HTML 中的资源

至此,我们已经将 DOM 树加载到 BeautifulSoup 对象中。接下来,让我们扫描 DOM 树,查找 JavaScript 文件,也就是脚本节点:

...
<script type='text/javascript' src='js/bootstrap.js'></script>
<script type='text/javascript' src='js/custom.js'></script>
...
Enter fullscreen mode Exit fullscreen mode

用于定位 JavaScript 代码的片段只有几行代码。BS 库会返回一个对象数组,我们可以轻松地修改每个脚本节点:

for script in soup.body.find_all('script', recursive=False):

   # Print the src attribute
   print(' JS source = ' + script['src'])

   # Print the type attribute
   print(' JS type = ' + script['type'])   

Enter fullscreen mode Exit fullscreen mode

类似地,我们可以选择并处理 CSS 节点:

...
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/app.css">
...
Enter fullscreen mode Exit fullscreen mode

还有代码……

for link in soup.find_all('link'):

   # Print the src attribute
   print(' CSS file = ' + script['href'])

Enter fullscreen mode Exit fullscreen mode

解析 HTML 中的图像

在这段代码片段中,我们将修改节点并更改src图像节点的属性。

...
<img src="images/pic01.jpg" alt="Bred Pitt">
...
Enter fullscreen mode Exit fullscreen mode
for img in soup.body.find_all('img'):

   # Print the path 
   print(' IMG src = ' + img[src]) 

   img_path = img['src']
   img_file = img_path.split('/')[-1] # extract the last segment, aka image file  
   img[src] = '/assets/img/' + img_file 
   # the new path is set 
Enter fullscreen mode Exit fullscreen mode

根据 ID 定位元素

这只需一行代码即可实现。假设我们有一个元素(div 或 span),其 id 为1234

...
<div id="1234" class="handsome">
Some text
</div>

Enter fullscreen mode Exit fullscreen mode

代码如下:

mydiv = soup.find("div", {"id": "1234"})

print(mydiv) 

# delete the element
mydiv.decompose()

Enter fullscreen mode Exit fullscreen mode

删除硬编码文本

这段代码片段可用于提取组件并将其转换为不同的模板引擎。假设我们有这样一个简单的组件:

<div id="1234" class="cool">
   <span>Html Parsing</span>
   <span>the practical guide</span> 
</div>
Enter fullscreen mode Exit fullscreen mode

如果要在 PHP 中使用此组件,则组件代码如下:

<div id="1234" class="cool">
   <span><?php echo $title ?></span>
   <span><?php echo $info ?></span> 
</div>
Enter fullscreen mode Exit fullscreen mode

或者对于 Jinja2(Python 模板引擎)

<div id="1234" class="cool">
   <span>{{ title }}</span>
   <span>{{ info }}</span> 
</div>
Enter fullscreen mode Exit fullscreen mode

为了避免手动操作,我们可以使用代码片段自动替换硬编码文本,并使组件适应特定的模板引擎:

# locate the div
mydiv = soup.find("div", {"id": "1234"})

print(mydiv) # print before processing

# iterate on div elements
for tag in mydiv.descendants:

   # NavigableString is the text inside the tag, 
   # not the tag himself 
   if not isinstance(tag, NavigableString):

      print( 'Found tag = ' + tag.name ' -> ' + tag.text )
      # this will print:
      # Found tag = span ->  Html Parsing
      # Found tag = span ->  the practical guide

      # replace the text for Php
      tag.text = '<?php echo $title ?>'

      # replace the text for Jinja
      tag.text = '{{ title }}'    
Enter fullscreen mode Exit fullscreen mode

要使用该组件,我们可以将其保存到文件中:


# mydiv is the processed component
php_component is the string representation
php_component = mydiv.prettify(formatter="html") 

file = open( 'component.php', 'w+') 
file.write( php_component )
file.close()

Enter fullscreen mode Exit fullscreen mode

此时,原始的 div 元素已从 DOM 中提取出来,硬编码的文本已被删除,可以用于 Php 或 Python 项目。


保存新的 HTML 代码

现在我们已经将修改后的 DOM 存储在 BeautifulSoup 对象中,并保存在内存中。要将内容保存到新文件,我们需要调用 `save()` 方法prettify()并将内容保存到新的 HTML 文件。


new_dom_content = soup.prettify(formatter="html") 

file = open( 'index_parsed.html', 'w+') 
file.write( new_dom_content )
file.close()

Enter fullscreen mode Exit fullscreen mode

HTML解析器- 应用案例

我经常使用 HTML 解析,尤其是在需要手动操作的任务中:

  • 处理新项目中使用的 HTML 主题
  • 提取硬编码文本并提取组件
  • 将扁平化的 HTML 主题转换为 Jinja、Mustache 或 PUG 模板

我会不定期地在这个公共代码库中发布免费示例。

资源


谢谢!如需更多资源和工具,请访问:

文章来源:https://dev.to/sm0ke/html-parser-extact-html-information-with-ease-308m