【问题标题】:scrapy / lxml.html : Consolidate multiple consecutive <br> tagsscrapy / lxml.html : 合并多个连续的 <br> 标签
【发布时间】:2018-03-10 21:30:21
【问题描述】:

我正在使用 Scrapy 从多个网站收集数据。我正在使用 w3lib.html.remove_tags 在我的 ScrapyField() 声明中使用 Compose 将 HTML 完全清除为基本格式标记:b、em、strong、i 和 br。然后我有一个管道将其重建为更干净、更统一的 HTML,以便在另一个网站上显示。

很多被抓取的 HTML 最终都有多个连续的 br 标签,每次出现我都需要将它们合并为一个 br 标签。这个问题的公认答案:Merge multiple <br /> tags to a single one with python lxml 完全做到了这一点,但是,只有当
标签不被空格分隔时。假设我的 ItemLoaders 之一返回以下字符串:

<div class="info"> <br>  <br> <p class="tight"><br> Some text</p><br>  <br></div>

上面引用的解决方案不适用于它们。怎么可能巩固这些?我正在寻找非 RegEx 解决方案。似乎lxml应该能够处理这个,但我不知道如何。

【问题讨论】:

  • 我没有想到任何非正则表达式的解决方案,你为什么不想使用正则表达式?
  • 有兴趣了解被否决的原因。

标签: python html scrapy lxml


【解决方案1】:

下面的代码对我来说很好用

from lxml import html
data = """
<div class="info"> <br>   <br> <br> <p class="tight"><br> Some text</p><br>  <br></div>
"""
doc = html.fromstring(data)
for br in doc.findall('.//br'):
    if br.tail is None or br.tail.strip() =='': # no text immediately after <br> tag
        for dup in br.itersiblings():
            if dup.tag != 'br': # don't merge if there is another tag inbetween
                break
            dup.drop_tag()
            if not (dup.tail is None or dup.tail.strip() == ''): # don't merge if there is a text inbetween
                break

print(html.tostring(doc))

输出:

b'<div class="info"> <br>     <p class="tight"><br> Some text</p><br>  </div>\n'

【讨论】:

  • 完美答案。这么简单,我不知道为什么我没有想到它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 2015-08-15
  • 2015-05-21
  • 1970-01-01
  • 2010-09-13
  • 2014-09-28
  • 1970-01-01
相关资源
最近更新 更多