2016-08-30 99 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本身。 –