<和第一个sp的python正则表达式

2024-03-28 16:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

这是html-

html_tag = <div class="profile-content large-9 columns end clearfix">
<h3>whatever</h3>
</div>

首先,我将转换成一个字符串,如str(html_tag.encode('utf-8')) 那我需要那个标签名。你知道吗

print re.search('<(.+?) ',str(html_tag.encode('utf-8'))).group(1)

这里的输出仅为'div'。基本上我是在'<;'和空格之间取子字符串。但是我得到了'NoneType' object has no attribute 'group'的错误。所以re.search('<(.+?) ',str(html_tag.encode('utf-8')))什么都不匹配。现在我如何更正这个正则表达式?你知道吗


Tags: 字符串divresearchhtmltaggroupcontent
2条回答

我假设你的“html\u标签”在标签.txt这样我就可以把下面的代码读入str

with open("tags.txt") as file:            
    data = file.read()

然后您可以将div标记与以下内容匹配

matched = re.match(r'<(.+?)\s', data)
print(matched.group(1))
div

此处“\s”用于匹配空格。你知道吗

相关问题 更多 >