【问题标题】:Scrapy. How to remove style attribute (class or id attribute) from tags in parsed HTML刮痧。如何从已解析 HTML 中的标签中删除样式属性(类或 id 属性)
【发布时间】:2015-10-29 18:35:17
【问题描述】:

刮擦。如何使用 lxml 帮助从已解析 HTML 中的标签中删除样式属性(类或 id 属性)?类似lxml.html.clean.Cleaner 或类似的东西:

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

【问题讨论】:

  • 您能否编辑您的问题并举例说明您得到了什么(使用您当前的代码)以及您想要什么?
  • 我需要解析带有标签的项目,而不仅仅是文本。并解析项目样式完整。例如: item['asterisk1'][0] = '
  • 1需要 InstantGo 或通过设备加密 HCK 测试的设备
  • '

标签: python html web-scraping scrapy


【解决方案1】:

您必须在蜘蛛文件中导入另一个内置 python 类

import lxml.html.clean as clean
safe_attrs = set(['src', 'alt', 'href', 'title', 'width', 'height'])
kill_tags = ['object', 'iframe']
cleaner = clean.Cleaner(safe_attrs_only=True, safe_attrs=safe_attrs, kill_tags=kill_tags)
html_string = "some html string with iframes, objects…"

然后像这样使用它

cleaned_html = cleaner.clean_html(html_string)

您可以将safe_attrskill_tags 自定义为要删除的任何属性和标签。

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签