python - 在 Python 中使用正则表达式匹配两个字符串中的 HTML 标签

标签 python html regex

我想验证源字符串中存在的 HTML 标记是否也存在于目标字符串中。

例如:

>> source = '<em>Hello</em><label>What's your name</label>'
>> verify_target(’<em>Hi</em><label>My name is Jim</label>')
True
>> verify_target('<label>My name is Jim</label><em>Hi</em>')
True
>> verify_target('<em>Hi<label>My name is Jim</label></em>')
False

最佳答案

我会摆脱 Regex 并查看 Beautiful Soup .
findAll(True) 列出在您的源代码中找到的所有标签。

from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup(source)
allTags = soup.findAll(True)
[tag.name for tag in allTags ]
[u'em', u'label']

然后您只需要删除可能的重复项并面对您的标签列表。

此代码段验证目标标签中是否存在所有源标签。

from BeautifulSoup import BeautifulSoup
def get_tags_set(source):
    soup = BeautifulSoup(source)
    all_tags = soup.findAll(True)
    return set([tag.name for tag in all_tags])

def verify(tags_source_orig, tags_source_to_verify):
    return tags_source_orig == set.intersection(tags_source_orig, tags_source_to_verify)

source= '<label>What\'s your name</label><label>What\'s your name</label><em>Hello</em>'
source_to_verify= '<em>Hello</em><label>What\'s your name</label><label>What\'s your name</label>'
print verify(get_tags_set(source),get_tags_set(source_to_verify))

关于python - 在 Python 中使用正则表达式匹配两个字符串中的 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2673059/

相关文章:

html - 使用文本对齐时的半边距 : center instead of text-align: left

java - 使用正则表达式替换字符串中的特定字符

regex - 否定正则表达式子表达式

c# - 如何使用维基百科中的超链接以编程方式制作 html 文本?

python - dask 将数据帧导出到远程存储(S3)

python - 如何使用 Django 在 nginx 中设置子目录

python - 是否可以在 python FPDF 中更改 PDF 的背景颜色?

python - 如何将 numpy 数组从 (128,128,3) 更改为 (3,128,128)?

javascript - HTML - 选择本地路径来移动文件

html - 如何去除边框?