从所有元素中删除所有带有etree的数据属性

时间:2019-03-11 09:04:44

标签: python python-3.x scrapy lxml elementtree

因此,我正在尝试清除一些HTML。我有以下功能:

def clean_html(self, html):
    replaced_html = html.decode('utf-8').replace('<', ' <')

    tree = etree.HTML(replaced_html)
    etree.strip_elements(tree, 'script', 'style', 'img', 'noscript', 'svg')

    for el in tree.xpath('//*[@style]'):
        el.attrib.pop('style')

    for el in tree.xpath('//*[@class]'):
        el.attrib.pop('class')

    for el in tree.xpath('//*[@id]'):
        el.attrib.pop('id')

    etree.strip_tags(tree, etree.Comment)
    return etree.tostring(tree, encoding='unicode', method='html')

我还希望删除所有data-attributes,例如

<li data-direction="ltr" '
         'data-listposition="center" data-data-id="dataItem-ifz7cqbs" '
         'data-state="menu idle link notMobile">sky</li>

但是我不知道这些属性(上面只是一个例子)。

因此,我希望将以上内容转换为<li>sky</li>,并将其运行在页面上的每个元素上。

在上面的代码中,我可以删除诸如idclass之类的简单内容,但是不确定如何处理动态属性data-*。可能是正则表达式?

编辑

我应该澄清一下输入内容。上面的示例显示了<li>标签的使用。但是实际的输入是页面的整个html,因此它类似于:

<html>
  <ul>
    <li data-i="sdfdsf">something</li>
    <li data-i="dsfd">something</li>
  </ul>
  <p data-para="cvcv">content</p>
 <div data-image-info='{"imageData":{"type":"Image","id":"dataItem-ifp35za1","metaData":{"pageId":"masterPage","isPreset":false,"schemaVersion":"2.0","isHidden":false},"title":"Black LinkedIn Icon","uri":"6ea5b4a88f0b4f91945b40499aa0af00.png","width":200,"height":200,"alt":"Black LinkedIn Icon","link":{"type":"ExternalLink","id":"dataItem-ig84dp5v","metaData":{"pageId":"masterPage","isPreset":false,"schemaVersion":"1.0","isHidden":false},"url":"https://www.linkedin.com/in/beth-liu-aba2b487?trk=hp-identity-name","target":"_blank"}},"displayMode":"fill"}' > </div> </a> </li> <li> <a href="https://www.pinterest.com/agencyb/" target="_blank"  > <div data-image-info='{"imageData":{"type":"Image","id":"dataItem-ijxtrrjj","metaData":{"pageId":"masterPage","isPreset":false,"schemaVersion":"2.0","isHidden":false},"title":"Black Pinterest Icon","uri":"8f6f59264a094af0b46e9f6c77dff83e.png","width":200,"height":200,"alt":"Black Pinterest Icon","link":{"type":"ExternalLink","id":"dataItem-ikg674xm","metaData":{"pageId":"masterPage","isPreset":false,"schemaVersion":"1.0","isHidden":false},"url":"https://www.pinterest.com/agencyb/","target":"_blank"}},"displayMode":"fill"}' > </div> </a> </li> <li> <a href="http://www.twitter.com/lubecka" target="_blank"  > <div data-image-info='{"imageData":{"type":"Image","id":"dataItem-ifp3554u","metaData":{"pageId":"masterPage","isPreset":false,"schemaVersion":"2.0","isHidden":false},"title":"Black Twitter Icon","uri":"c7d035ba85f6486680c2facedecdcf4d.png","description":"","width":200,"height":200,"alt":"Black Twitter Icon","link":{"type":"ExternalLink","id":"dataItem-ifp3554u1","metaData":{"pageId":"masterPage","isPreset":false,"schemaVersion":"1.0","isHidden":false},"url":"http://www.twitter.com/lubecka","target":"_blank"}},"displayMode":"fill"}' > </div> </a> </li> <li> <a href="https://www.instagram.com/" target="_blank">
<html>

3 个答案:

答案 0 :(得分:2)

假设“数据属性”的名称始终以“ data-”开头,则可以这样删除它们:

for el in tree.xpath("//*"):
    for attr in el.attrib:
        if attr.startswith("data-"):
            el.attrib.pop(attr)

答案 1 :(得分:0)

您可以像这样清除属性


import re
def strip_attribute(data):
    p = re.compile('data-[^=]*="[^"]*"')
    print(p)
    return p.sub('', data)
print(strip_attribute('with attribute'))

答案 2 :(得分:0)

也许这就是您想要的:

from lxml import etree

code = """
 <html>
   <ul>
    <li data-i="sdfdsf">something</li>
    <li data-i="dsfd">something</li>
  </ul>
    <p data-para="cvcv">content</p> 
</html>

"""

xml = etree.XML(code)
elements = list(xml.iter())
for element in elements:
   if len(element.text.strip())>0:
      print('<'+element.tag+'>'+element.text+'</'+element.tag+'>')

输出:

<li>something</li>
<li>something</li>
<p>content</p>