【问题标题】:Python. How to find all occurrences of matched substring?Python。如何找到所有匹配的子字符串?
【发布时间】:2016-10-24 08:53:54
【问题描述】:

我有一个大字符串 - html 页面。我需要找到闪存驱动器的所有名称, 即我需要在双引号之间获取内容:data-name="USB Flash-drive Leef Fuse 32Gb">。所以我需要一个介于data-name=" 和"> 之间的字符串。请不要提BeautifulSoup,我需要不用BeautifulSoup,最好不用正则表达式,但也接受正则表达式。

我试过用这个:

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

但结果为无。 但是在 regex101.com 上它起作用了:

【问题讨论】:

  • 在 HTML 上使用 DOM 解析器来提取属性值有什么问题?
  • @Vasili Syrakis 我有某些任务 - 使用 python 完成。
  • 仅供参考 bs4 = python ;请参阅此链接的第一段:crummy.com/software/BeautifulSoup/bs4/doc
  • @dot.Py 我知道 bs4 是 python,但我需要在没有 bs4 的帮助下完成它,只有 pythons 内置函数或至少是正则表达式。
  • Python标准库有htmparser(py3中的html.parser)可以在这里使用。

标签: python regex python-3.x html-parsing


【解决方案1】:

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>')

输出:

USB Flash-drive Leef Fuse 32Gb

我在代码中添加了一些 cmets,以向您展示解析器返回的数据结构类型。

从这里开始构建应该很容易。

只需输入 HTML,它就会很好地解析它。请参阅文档,并继续尝试。

【讨论】:

  • 非常感谢,上帝保佑你。
【解决方案2】:

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

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

这就是我的 python shell 中发生的事情

>>> s='junk...data-name="USB Flash-drive Leef Fuse 32Gb">...junk'
>>> start = s.find('data-name="')
>>> end = s.find('">')
>>> output = s[start:end]
>>> output
'data-name="USB Flash-drive Leef Fuse 32Gb'

如果这部分脚本单独工作,请告诉我

【讨论】:

  • 如果你还在寻找替代解决方案,你可以粘贴你的长 html 字符串让我测试
  • 这里是一个 py 文件,它从站点获取闪存驱动器并将它们放入 intro 'html_str' 字符串:dropmefiles.com/wBvb1
猜你喜欢
  • 1970-01-01
  • 2022-07-16
  • 2013-06-22
  • 2015-01-11
  • 2015-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
相关资源
最近更新 更多