【问题标题】:Using regex to extract all the html attrs使用正则表达式提取所有 html attrs
【发布时间】:2013-06-25 17:10:27
【问题描述】:

我想使用re 模块从字符串中提取所有 html 节点,包括它们的所有属性。但是,我希望每个 attr 都是一个组,这意味着我可以使用 matchobj.group() 来获取它们。节点中的属性数量是灵活的。这就是我感到困惑的地方。我不知道如何编写这样的正则表达式。我已经尝试过</?(\w+)(\s\w+[^>]*?)*/?>',但是对于像<a href='aaa' style='bbb'> 这样的节点,我只能使用[('a'), ('style="bbb")] 获得两个组。
我知道有一些很好的 HTML 解析器。但实际上我不会提取 attrs 的值。我需要修改原始字符串。

【问题讨论】:

标签: python html regex


【解决方案1】:

Please don't use regex。使用BeautifulSoup

>>> from bs4 import BeautifulSoup as BS
>>> html = """<a href='aaa' style='bbb'>"""
>>> soup = BS(html)
>>> mytag = soup.find('a')
>>> print mytag['href']
aaa
>>> print mytag['style']
bbb

或者如果你想要一本字典:

>>> print mytag.attrs
{'style': 'bbb', 'href': 'aaa'}

【讨论】:

  • 我知道 HTML 解析器应该是不错的选择,但实际上我认为它们不适合我。我需要修改原始字符串。
  • @zhangyangyu 看看this或许
【解决方案2】:

说明

要捕获无限数量的属性,它需要一个两步过程,其中首先拉取整个元素。然后您将遍历元素并获取匹配属性的数组。

获取所有元素的正则表达式:&lt;\w+(?=\s|&gt;)(?:[^&gt;=]|='[^']*'|="[^"]*"|=[^'"][^\s&gt;]*)*?&gt;

从单个元素中获取所有属性的正则表达式:\s\w+=(?:'[^']*'|"[^"]*"|[^'"][^\s&gt;]*)(?=\s|&gt;)

Python 示例

查看工作示例:http://repl.it/J0t/4

代码

import re

string = """
<a href="i.like.kittens.com" NotRealAttribute=' true="4>2"' class=Fonzie>text</a>
""";

for matchElementObj in re.finditer( r'<\w+(?=\s|>)(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*?>', string, re.M|re.I|re.S):
    print "-------"
    print "matchElementObj.group(0) : ", matchElementObj.group(0)

    for matchAttributesObj in re.finditer( r'\s\w+=(?:\'[^\']*\'|"[^"]*"|[^\'"][^\s>]*)(?=\s|>)', string, re.M|re.I|re.S):
        print "matchAttributesObj.group(0) : ", matchAttributesObj.group(0)

输出

-------
matchElementObj.group(0) :  <a href="i.like.kittens.com" NotRealAttribute=' true="4>2"' class=Fonzie>
matchAttributesObj.group(0) :   href="i.like.kittens.com"
matchAttributesObj.group(0) :   NotRealAttribute=' true="4>2"'
matchAttributesObj.group(0) :   class=Fonzie

【讨论】:

    猜你喜欢
    • 2019-06-05
    • 2012-04-27
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    相关资源
    最近更新 更多