2017-05-28 387 views
0

后,我有一个循环:添加标签当前BeautifulSoup

for tag in soup.find('article'): 

我需要在这个循环中每个标签后面添加新的标签,我试图用insert()方法,但我没有管理。

如何用BeautifulSoup解决此任务?

+0

'的标签在soup.find(“”)'不会返回你希望它在这个例子中返回的内容 - 'soup.find('')'返回一个单独的标签。因此,'soup.find()'调用之前的'for tag'实际上是指示Python遍历标签中的单个元素,而不是您要定位的元素中的所有标签。 – n1c9

+0

你必须看看[BeautifulSoup文档](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring-and-new-tag) –

回答

4

您可以使用insert_after,并且还您可能需要find_all,而不是find如果您正试图通过节点集合迭代:

from bs4 import BeautifulSoup 
soup = BeautifulSoup("""<article>1</article><article>2</article><article>3</article>""") 

for article in soup.find_all('article'): 

    # create a new tag 
    new_tag = soup.new_tag("tagname") 
    new_tag.append("some text here") 

    # insert the new tag after the current tag 
    article.insert_after(new_tag) 

soup 

<html> 
    <body> 
     <article>1</article> 
     <tagname>some text here</tagname> 
     <article>2</article> 
     <tagname>some text here</tagname> 
     <article>3</article> 
     <tagname>some text here</tagname> 
    </body> 
</html> 
+0

insert_after - cool!如何在文章的任何孩子之后添加新标签? – nueq

+0

您可能需要append方法,就像文本如何添加到新标签中一样。 'another_new_tag = soup.new_tag(...); article.append(another_new_tag);' – Psidom