2015-12-07 39 views
0

這裏分解代碼的HTML部分是輸入HTML片段:我試圖用BeautifulSoup

<p>both before<img src="it is free"style="width:590px;height:228px;"> and after img tag</p> 

下面是所需的輸出片段:

<p> both before </p><img src="it is free"style="width:590px;height:228px;"><p>after img tag</p> 

這裏是我的代碼片段:

from bs4 import BeautifulSoup 
from bs4 import NavigableString 
while len(p_tag.contents) != 0: 
    item = p_tag.contents.pop(0) 
    if isinstance(item, NavigableString): 
     new_tag = doc.new_tag('p') 
     new_tag.string = item 
     current_tag.insert_after(new_tag) 
     current_tag = current_tag.next_sibling 
    else: 
     new_tag = item 
     current_tag.insert_after(new_tag) 
     current_tag = current_tag.next_sibling 

但我得到以下錯誤,雖然我很確定我有標記內容:

 raise ValueError("Tag.index: element not in tag") 
    ValueError: Tag.index: element not in tag 

請使用 'html5lib' 作爲BeautifulSoup前解析器:

doc = BeautifulSoup(open(input_doc), 'html5lib') 

有什麼辦法來擺脫這種錯誤的? 在此先感謝。

回答

0

這裏是代碼的工作版本:

p_tag_contents = p_tag.contents 
current = p_tag 
for i in range(len(p_tag_contents)): 
    item = copy.copy(p_tag_contents[i]) 
    if isinstance(item, NavigableString): 
     new_element = doc.new_tag('p') 
     new_element.string = item 
     current.insert_after(new_element) 
     current = current.next_sibling 
    else: 
     current.insert_after(item) 
     current = current.next_sibling 
p_tag.decompose() 

是先得到一個定標籤的所有內容,然後給定的標籤後插入他們終於摧毀定標籤,我們需要做什麼。我在這裏使用拷貝的原因是沒有複製導致編程錯誤的每次迭代中的內容變化。