我想验证源字符串中存在的 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/