2016-08-30 107 views
1

我是BeautifulSoup的完全初學者,我現在正嘗試將新標籤插入父DIV的子DIV中。BeautifulSoup在父DIV的子DIV中添加新標籤

基本上我有這個HTML片段:

<div class=page-content> 
    <div class="content-block"> 
    //Insert here! 
    </div> 
</div> 

這裏是我當前的代碼:

soup = BeautifulSoup(open("index.html"), "lxml") 

    div_page_content = soup.find("div", { "class" : "page-content" }) 
    content_block = div_page_content.findChildren() 

    button_active = soup.new_tag('a') 
    button_active.attrs['class'] = 'button active' 
    button_active.append('This is a new button!') 

    content_block.append(button_active) 
    print content_block 

我可以抓取網頁的內容和他的孩子們的內容塊DIV,但附加功能沒有做任何事情,這是我得到的輸出:

[<div class="content-block">\n</div>, <a class="button active">This is a new button!</a>] 

回答

0

發現問題,我必須使用findNext而不是findChildren。現在追加工作正常。

-1

你確定錯誤不是你在課堂上留下了引號嗎?你寫了<div class=page-content> 而不是<div class="page-content">

+1

這是[完全有效的HTML](https://mathiasbynens.be/notes/unquoted-attribute-values),並不是OP的*** python ***問題的原因。 – Toastrackenigma

+0

我暗指BeautifulSoup,他們的編碼器曾經與引號糾纏,而不是HTML本身。 –