【问题标题】:Python re.sub replace html attributesPython re.sub 替换 html 属性
【发布时间】:2017-08-07 20:14:42
【问题描述】:

我正在尝试从 html 代码调整图像的大小。这是一个例子:

我的目标是用高度和宽度 400 替换 " height="108" " 和 " width="150"。 我尝试了以下几行,但它们似乎不起作用:

re.sub(r'width="[0-9]{2,4}"','width="400"',x)
re.sub(r'height="[0-9]{2,4}"','height="400"',x)

有人对此有解决方案吗? Ps:我不太擅长正则表达式... :)

【问题讨论】:

  • Nooo...不要使用正则表达式解析/修改 html/xml...使用 BeautifulSoup/XSLT/...等工具。
  • 这并不能完全回答我的问题,虽然我会看看它:)
  • Python 字符串是不可变的。子函数返回一个新字符串
  • 正则表达式适用于这个特定的用例。
  • Re.sub not working for me的可能重复

标签: python html regex


【解决方案1】:

它不起作用的原因是因为字符串是不可变的,并且您不处理结果。您可以通过以下方式“解决”问题:

x = re.sub(r'width="[0-9]{2,4}"','width="400"',x)
x = re.sub(r'height="[0-9]{2,4}"','height="400"',x)

话虽如此使用正则表达式处理 HTML/XML 是一个非常糟糕的主意。假设你有一个标签<foo altwidth="1234">。现在您将其更改为<foo altwidth="400"> 您想要吗?应该不会吧。

例如,您可以使用 BeautifulSoup

soup = BeautifulSoup(x,'lxml')

for tag in soup.findAll(attrs={"width":True})
    tag.width = 400
for tag in soup.findAll(attrs={"height":True})
    tag.height = 400
x = str(soup)

在这里,我们将带有width 属性的所有 标记替换为width="400",并将所有带有height 的标记替换为height="400"。您可以通过例如只接受<img>标签来使其更高级,例如:

soup = BeautifulSoup(x,'lxml')

for tag in soup.findAll('img',attrs={"width":True})
    tag.width = 400
for tag in soup.findAll('img',attrs={"height":True})
    tag.height = 400
x = str(soup)

【讨论】:

    【解决方案2】:

    似乎工作正常:

    >>> x = '<foo width="150" height="108">'
    >>> import re
    >>> y = re.sub(r'width="[0-9]{2,4}"','width="400"',x)
    >>> y
    '<foo width="400" height="108">'
    

    请注意,re.sub 不会改变 x:

    >>> x
    '<foo width="150" height="108">'
    >>> y
    '<foo width="400" height="108">'
    

    也许你想这样做:

    x = re.sub(r'width="[0-9]{2,4}"','width="400"',x)
    x = re.sub(r'height="[0-9]{2,4}"','height="400"',x)
    

    【讨论】:

    • 顺便标记了一个重复项
    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 2017-07-21
    • 2019-05-16
    • 2015-12-18
    • 2012-08-15
    • 2015-11-17
    相关资源
    最近更新 更多