2017-05-28 94 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