有这样的html
somehtml = "<p>Here is my solution: </p><pre><code> some code here </code> </pre> <pre>this is not a code</pre>"
通过python我想将类“foo”添加到包含子<pre>
的{{1}}标签中,因此我的输出将是:
<code>
我怎样才能做到这一点?
答案 0 :(得分:4)
使用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>