首页 > 解决方案 > 如何使用 python 从内联样式标签中删除特定的值对?

问题描述

我正在尝试解析一些具有一些讨厌的内联样式的 html。它看起来像这样

<span class="text_line" data-complex="0" data-endposition="4:2:86:5:0" data-position="4:2:74:2:0" style="font-family: scala-sans-offc-pro--; width: 100%; word-spacing: -2.66667px; font-size: 24px !important; line-height: 40px; font-variant-ligatures: common-ligatures; display: block; height: 40px; margin-left: 75px; margin-right: 155px;">

我正在尝试仅删除属性值对word-spacing: -2.66667px;。这里有几百条这样的线,没有两条是相同的。有时间距是word-spacing: -4px有时word-spacing: -3.78632px;或其他一些随机数。

我尝试了美丽的汤,我想出了如何去除整个标签,这不是我想要的。我不知道如何用正则表达式来做到这一点。而且我读到最好避免尝试使用正则表达式编辑 HTML。

我的想法是使用漂亮的汤将所有跨度标签保存到一个变量中,然后string.find()用于获取所有“w”在字间距中的索引,然后找到下一个半列。然后在我有一个列表之后,找到一种方法来切割这些索引处的字符串并将剩余部分重新连接在一起。也许在“;”处分裂 更好......我现在不知道了。大脑又炸又累。:P

    def __init__(self, first_index, last_index):
        self.first = first_index
        self.last = last_index
def getIndices(text, start_index):
    index = CutPointIndex(None, None)
    index.first = text.find("word-spacing", start_index, end_index)
    if(index.first != -1):
        index.last = text.find(";", index.first , end_index)
    return index

鉴于类似 style="font-family: scala-sans-offc-pro--; width: 100%; word-spacing: -3.71429px;"

或者 style="font-family: scala-sans-offc-pro--; width: 100%; word-spacing: -5px;

或任何其他值的变化预期的结果应该是 style="font-family: scala-sans-offc-pro--; width: 100%;

标签: pythonregexstringparsingbeautifulsoup

解决方案


您可以匹配具有该属性的元素并删除该部分。

我拆分样式属性(仅适用于相关标签);然后重新组合排除不需要的对

';'.join([i for i in t['style'].split(';') if 'word-spacing' not in i])

但您也可以轻松地更新word-spacing

from bs4 import BeautifulSoup as bs

html = '''
<span class="text_line" data-complex="0" data-endposition="4:2:86:5:0" data-position="4:2:74:2:0" style="font-family: scala-sans-offc-pro--; width: 100%; word-spacing: -2.66667px; font-size: 24px !important; line-height: 40px; font-variant-ligatures: common-ligatures; display: block; height: 40px; margin-left: 75px; margin-right: 155px;">
'''
soup = bs(html, 'lxml')

for t in soup.select('[style*= word-spacing]'):
    t['style'] = ';'.join([i for i in t['style'].split(';') if 'word-spacing' not in i])
print(soup)

阅读:

  1. https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes
  2. https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

推荐阅读