2016-09-19 87 views
1

我想在兩個段落之間自動插入一個html標籤以用於上千個類似的頁面。這段代碼是這樣的(新標籤必須插在標題類的段落之後):美麗的湯:在兩段落之間插入HTML5標籤

<p align="center"><span class="header">My Title</span></p> 
{insert new tag <article> here} 
<p align="center">bla-bla-bla</p> 

我正在使用Python和美麗的湯。我的困難是找到插入的位置以及如何在兩段之間插入。這是我迄今爲止還沒有正常工作的代碼。任何幫助?

soup = BeautifulSoup(page, 'html.parser') 
cells = soup.findAll('p', attrs={"class":"header"}) 
index=str(cells).index('</p><p>') # search location between two paragraphs 
output_line = cells[:index] + '<article> ' + cells[index:] 

回答

1

哇,作爲核心代碼由Trombone展示。我想給出更完整的演示。

from bs4 import BeautifulSoup 
page = """ 
<p align="center"><span class="header">My Title1</span></p> 
<p align="center">bla-bla-bla</p> 
<p align="center"><span class="header">My Title2</span></p> 
<p align="center">bla-bla-bla</p> 
<p align="center"><span class="header">My Title3</span></p> 
<p align="center">bla-bla-bla</p> 
""" 
soup = BeautifulSoup(page, "html.parser") 
for header in soup.find_all('span', class_='header'): 
    article = soup.new_tag('article') 
    article.string = 'article content' 
    header.insert_after(article) 

print soup.prettify() 

OUTPUT:

<p align="center"> 
<span class="header"> 
    My Title1 
</span> 
</p> 
<article> 
article content 
</article> 
<p align="center"> 
bla-bla-bla 
</p> 
<p align="center"> 
<span class="header"> 
    My Title2 
</span> 
</p> 
<article> 
article content 
</article> 
<p align="center"> 
bla-bla-bla 
</p> 
<p align="center"> 
<span class="header"> 
    My Title3 
</span> 
</p> 
<article> 
article content 
</article> 
<p align="center"> 
bla-bla-bla 
</p> 
1

試試這個:

soup = BeautifulSoup(page, 'html.parser') 
p = soup.find('span', {'class': 'header'}).parent 
p.insert_after(soup.new_tag('article')) 

就讓我們來看看在BeautifulSoup documentation得到很多有用的輔助方法,這些類的東西。

+0

哇。非常感謝你! – Hajar

+0

沒問題!如果此答案(或其他!)解決了您的問題,則可以通過單擊綠色複選標記將其標記爲「已接受」。 – 2016-09-20 09:18:33