【问题标题】:Python 3: How to add <p> before and after all img tags in html [duplicate]Python 3:如何在html中的所有img标签之前和之后添加<p> [重复]
【发布时间】:2019-10-18 02:24:05
【问题描述】:

对于html,我需要在img标签前后添加一个p标签。 每个 html 包含多个图像。

例如:

<br><img id="aimg_uhkH3" class="zoom" src="../Images/0001.jpg" border="0" alt="" width="430" height="20"><br>
foo <img id="acvdojj2" class="zoom" src="../Images/0002.jpg" width="430" height="20" border="0" alt=""> foo 

期望的结果:

<br><p><img id="aimg_uhkH3" class="zoom" src="../Images/0001.jpg" border="0" alt="" width="430" height="20"><p><br>
foo <p><img id="acvdojj2" class="zoom" src="../Images/0002.jpg" width="430" height="20" border="0" alt=""><p> foo

我无法用正则表达式得到它。

我的失败代码:(test_str 是 html 字符串)

re.sub(r'(<img.*>)','<p>\\1<p>',test_str)

我的失败结果:

<br><p><img id="aimg_uhkH3" class="zoom" src="../Images/0001.jpg" border="0" alt="" width="430" height="20"><br><p>
foo <p><img id="acvdojj2" class="zoom" src="../Images/0002.jpg" width="430" height="20" border="0" alt=""><p> foo

有什么提示吗?提前致谢。

【问题讨论】:

  • 试试re.sub(r'(&lt;img.*?&gt;)','&lt;p&gt;\\1&lt;p&gt;',test_str) 注意?
  • 如果您使用&lt;foo[^&gt;]+&gt; 等,HTML 会更简单一些。

标签: python html regex


【解决方案1】:

你的比赛迟到了。使用.*? 将使您的比赛在第一个&gt; 而不是最后一个&gt; 结束

re.sub(r'(<img.*?>)','<p>\\1<p>',test_str)

【讨论】:

  • 使用正则表达式来解析和操作 HTML 通常是不好的做法。
  • @TimBiegeleisen 同意,我的回答将在 &lt;img title="&gt;" ...&gt; 之类的问题上失败
  • @TimBiegeleisen zzz
猜你喜欢
  • 2017-06-14
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 2012-08-26
相关资源
最近更新 更多