【问题标题】:adding a class via python通过python添加一个类
【发布时间】:2011-01-22 12:32:34
【问题描述】:

有这样的html

somehtml = "<p>Here is my solution: </p><pre><code> some code here </code> </pre> <pre>this is not a code</pre>"

通过python,我想将类“foo”添加到那些包含子&lt;code&gt;&lt;pre&gt; 标签中,因此我的输出将是:

somehtml = "<p>Here is my solution: </p><pre class="foo"><code> some code here </code> </pre> <pre>this is not a code</pre>"

我怎样才能做到这一点?

【问题讨论】:

  • 您是在自己创建 HTML 吗?
  • 是的,我通过 wmd 编辑器创建它以降价并在服务器级别转换为 html 和 google-code-prettify 语法突出显示,我需要在 pre 标签中添加“prettyprint”类

标签: python html


【解决方案1】:

使用lxml,可以这样做:

import lxml.html as lh
import io

somehtml = "<p>Here is my solution: </p><pre><code> some code here </code> </pre> <pre>this is not a code</pre>"

doc=lh.parse(io.BytesIO(somehtml))
root=doc.getroot() 
pres=root.xpath('//pre/code/..')

for pre in pres:
    pre.attrib['class']='foo'
print(lh.tostring(root))

产量

<html><body><p>Here is my solution: </p><pre class="foo"><code> some code here </code> </pre> <pre>this is not a code</pre></body></html>

【讨论】:

  • 文件 "deneme.py",第 11 行,在 ''') 文件 "lxml.etree.pyx",第 1317 行,在 lxml.etree._Element.xpath (src/lxml /lxml.etree.c:37255) 文件“xpath.pxi”,第 289 行,在 lxml.etree.XPathElementEvaluator.__call__ (src/lxml/lxml.etree.c:104028) 文件“xpath.pxi”,第 212 行,在 lxml.etree._XPathEvaluatorBase._handle_result (src/lxml/lxml.etree.c:103335) 文件“xpath.pxi”,第 198 行,在 lxml.etree._XPathEvaluatorBase._raise_eval_error (src/lxml/lxml.etree.c: 103207) lxml.etree.XPathEvalError:无效的表达式
  • 我收到这样的错误,我认为 xpath 中的字符串有问题。
  • @Hellnar:很抱歉——我的错误。上面的编辑不应该有那个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 2015-03-25
  • 1970-01-01
  • 2012-10-29
  • 2015-09-04
  • 2017-12-02
  • 1970-01-01
相关资源
最近更新 更多