後,我有一個循環:添加標籤當前BeautifulSoup
for tag in soup.find('article'):
我需要在這個循環中每個標籤後面添加新的標籤,我試圖用insert()
方法,但我沒有管理。
如何用BeautifulSoup解決此任務?
後,我有一個循環:添加標籤當前BeautifulSoup
for tag in soup.find('article'):
我需要在這個循環中每個標籤後面添加新的標籤,我試圖用insert()
方法,但我沒有管理。
如何用BeautifulSoup解決此任務?
您可以使用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>
'的標籤在soup.find(「」)'不會返回你希望它在這個例子中返回的內容 - 'soup.find('')'返回一個單獨的標籤。因此,'soup.find()'調用之前的'for tag'實際上是指示Python遍歷標籤中的單個元素,而不是您要定位的元素中的所有標籤。 –
n1c9
你必須看看[BeautifulSoup文檔](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring-and-new-tag) –