擅长:python、mysql、java
<p>这将在每个<code><a>...</a></code>元素的末尾插入一个<code><br></code>标记:</p>
<pre><code>from BeautifulSoup import BeautifulSoup, Tag
# ....
soup = BeautifulSoup(data)
for a in soup.findAll('a'):
a.parent.insert(a.parent.index(a)+1, Tag(soup, 'br'))
</code></pre>
<p>不能使用<code>soup.findAll(tag = '</a>')</code>,因为BeautifulSoup不单独操作结束标记-它们被视为同一元素的一部分。</p>
<hr/>
<p>如果您想按照您在注释中的要求将<code><a></code>元素放入<code><p></code>元素中,可以使用以下命令:</p>
<pre><code>for a in soup.findAll('a'):
p = Tag(soup, 'p') #create a P element
a.replaceWith(p) #Put it where the A element is
p.insert(0, a) #put the A element inside the P (between <p> and </p>)
</code></pre>
<p>同样,您不会分别创建<code><p></code>和<code></p></code>,因为它们是同一事物的一部分。</p>