Python。如何找到匹配子串的所有匹配项?

2024-09-20 07:01:50 发布

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

我有一个很大的字符串-html页面。我需要找到所有闪存驱动器的名称, i、 我需要获取双引号之间的内容:data-name="USB Flash-drive Leef Fuse 32Gb">。所以我需要一个介于data-name="">之间的字符串。请不要提BeautifulSoup,我需要在没有beauthulsoup的情况下这样做,没有正则表达式更好,但是正则表达式也是可以接受的。在

我试着用这个:

p = re.compile('(?<=")[^,]+(?=")')
result = p.match(html_str)
print(result)

但结果并没有。 但在regex101.com上,它奏效了: enter image description here


Tags: 字符串name名称内容datahtml页面drive
2条回答

如果你想用基本的python字符串解析来做,这里是一种方法

s="html string"
start = s.find('data-name="')
end = s.find('">')
output = s[start:end]

这就是在我的pythonshell中发生的事情

^{pr2}$

让我知道这部分脚本是否单独工作

py2:https://docs.python.org/2/library/htmlparser.html

py3:https://docs.python.org/3/library/html.parser.html


from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        # tag = 'sometag'
        for attr in attrs:
            # attr = ('data-name', 'USB Flash-drive Leef Fuse 32Gb')
            if attr[0] == 'data-name':
                print(attr[1])

parser = MyHTMLParser()
parser.feed('<sometag data-name="USB Flash-drive Leef Fuse 32Gb">hello  world</sometag>')

输出:

^{pr2}$

我在代码中添加了一些注释,以显示解析器返回的数据结构类型。在

从这里建造应该很容易。在

只要输入HTML,它就能很好地解析它。参考文件,继续尝试。在

相关问题 更多 >