Python 提取HTML标签之间的字符串的程序
HTML标签用于设计网站的框架。我们通过标签内的字符串来传递信息和上传内容。位于HTML标签之间的字符串决定了浏览器如何显示和解释元素。因此,提取这些字符串在数据处理和操作中起着至关重要的作用。我们可以分析和理解HTML文档的结构。
这些字符串揭示了构建网页的隐藏模式和逻辑。在本文中,我们将处理这些字符串。我们的任务是提取HTML标签之间的字符串。
理解问题
我们需要提取所有HTML标签之间的字符串。我们的目标字符串被不同类型的标签包围,只有内容部分应该被检索到。让我们通过一个示例来理解。
输入输出场景
让我们考虑一个字符串-
Input:
Inp_STR = "<h1>This is a test string,</h1><p>Let's code together</p>"
输入的字符串包含不同的HTML标签,我们必须提取它们之间的字符串。
Output: [" This is a test string, Let's code together "]
我们可以看到,<h1>
和<p>
标记被移除,字符串被提取出来。现在我们已经理解了问题,让我们讨论一些解决方案。
使用迭代和replace()方法
这种方法专注于消除和替换HTML标记。我们将传入一个字符串和一个不同的HTML标记列表。接着,我们将把这个字符串初始化为列表的一个元素。
我们将遍历标记列表中的每个元素,并检查它是否存在于原始字符串中。我们将传入一个“ pos ”变量,它将存储索引值并驱动迭代过程。
我们将使用“ replace() ”方法将每个标记替换为空格,并得到一个不含HTML标记的字符串。
示例
以下是一个提取HTML标记之间字符串的示例:
Inp_STR = "<h1>This is a test string,</h1><p>Let's code together</p>"
tags = ["<h1>", "</h1>", "<p>", "</p>", "<b>", "</b>", "<br>"]
print(f"This is the original string: {Inp_STR}")
ExStr = [Inp_STR]
pos = 0
for tag in tags:
if tag in ExStr[pos]:
ExStr[pos] = ExStr[pos].replace(tag, " ")
pos += 1
print(f"The extracted string is : {ExStr}")
输出
This is the original string: <h1>This is a test string,</h1><p>Let's code together</p>
The extracted string is : [" This is a test string, Let's code together "]
使用正则表达式模块+findall()
在这个方法中,我们将使用正则表达式模块匹配一个特定的模式。我们将传入一个正则表达式:<"+tag+">(.*?)</"+tag+">
,它代表目标模式。该模式旨在捕获开头和结尾标签。在这里,“ tag ”是一个变量,它通过循环从标签列表中获取值。
“ findall() ”函数用于在原始字符串中找到模式的所有匹配项。我们将使用“ extend() ”方法将所有“匹配项”添加到一个新的列表中。通过这种方式,我们将提取包含在HTML标签中的字符串。
示例
下面是一个示例 −
import re
Inp_STR = "<h1>This is a test string,</h1><p>Let's code together</p>"
tags = ["h1", "p", "b", "br"]
print(f"This is the original string: {Inp_STR}")
ExStr = []
for tag in tags:
seq = "<"+tag+">(.*?)</"+tag+">"
matches = re.findall(seq, Inp_STR)
ExStr.extend(matches)
print(f"The extracted string is: {ExStr}")
输出
This is the original string: <h1>This is a test string,</h1><p>Let's code together</p>
The extracted string is: ['This is a test string,', "Let's code together"]
使用迭代和find()
在这种方法中,我们将使用“find()”方法在原始字符串中获取开放和封闭标签的第一个出现。我们将迭代标签列表中的每个元素并检索其在字符串中的位置。
我们将使用While循环在字符串中继续搜索HTML标签。我们将建立一个条件来检查字符串中是否存在不完整的标签。在每次迭代中,索引值被更新以找到下一个开启和关闭标签的出现位置。
所有开放和封闭标签的索引值都被存储,一旦整个字符串映射完成,我们使用字符串切片来提取HTML标签之间的字符串。
示例
以下是一个示例 –
Inp_STR = "<h1>This is a test string,</h1><p>Let's code together</p>"
tags = ["h1", "p", "b", "br"]
ExStr = []
print(f"The original string is: {Inp_STR}")
for tag in tags:
tagpos1 = Inp_STR.find("<"+tag+">")
while tagpos1 != -1:
tagpos2 = Inp_STR.find("</"+tag+">", tagpos1)
if tagpos2 == -1:
break
ExStr.append(Inp_STR[tagpos1 + len(tag)+2: tagpos2])
tagpos1 = Inp_STR.find("<"+tag+">", tagpos2)
print(f"The extracted string is: {ExStr}")
输出
The original string is: <h1>This is a test string,</h1><p>Let's code together</p>
The extracted string is: ['This is a test string,', "Let's code together"]
结论
在本文中,我们讨论了许多从HTML标签中提取字符串的方法。我们从简单的解决方案开始,使用空格定位和替换标签。我们还使用了regex模块及其 findall() 方法来查找匹配模式的结果。我们对 find() 方法和字符串切片的应用有了更好的理解。