2016-06-18 22 views
0

私はPythonには初めてですが、これまで言語を楽しんでいます。Python BeautifulSoup html5lib mixは、forループ内の他のすべてのアイテムを削除しているようです。

私は複雑なhtml5要素を作成し、html5libモジュールを使用しています。

私はパラグラフの要素を調べるとうまく印刷できますが、bs4の挿入方法を試してみると、他の要素の出力がすべて得られますが、その理由はわかりません。

私のpython:

i = 0 
    for gallery_elem in gallery_header_next_sibling: 
     if (gallery_elem.name.lower() == 'img'): 
      if (i == 0): 
       new_gallery = soup.new_tag("div") 
       new_gallery[ "class" ] = "gallery" 

      new_gallery_elem = soup.new_tag("figure") 

      if (gallery_elem.has_attr("alt")): 
       new_gallery_cap = soup.new_tag("figcaption") 
       new_gallery_cap.string = gallery_elem[ "alt" ] 
       new_gallery_elem.insert(2, new_gallery_cap) 

      if (gallery_elem.has_attr("title")): 
       new_gallery_attribution = soup.new_tag("dl") 
       new_gallery_attribution_dt = soup.new_tag("dt") 
       new_gallery_attribution_dt.string = "Image owner:" 
       new_gallery_attribution_dd = soup.new_tag("dd") 
       new_gallery_attribution_dd.string = gallery_elem[ "title" ] 
       new_gallery_attribution.insert(0, new_gallery_attribution_dt) 
       new_gallery_attribution.insert(1, new_gallery_attribution_dd) 

     new_gallery_elem.insert(1, new_gallery_attribution) 
     new_gallery_elem.insert(1, gallery_elem) 
     i = i + 1 

    new_gallery_elem.insert(1, gallery_elem) 

HTML

<img alt="Caption One." src="img/orange.jpg" title="Attribution One."/> 
<img alt="Caption Two." src="img/red.jpg" title="Attribution Two."/> 
<img alt="Caption Three." src="img/urban.jpg" title="Attribution Three."/> 
<img alt="Caption Four." src="img/brolly.jpg" title="Attribution Four."/> 
<img alt="Caption Five." src="img/tomy.jpg" title="Attribution Five."/> 

出力:

<figure><figcaption>Caption One.</figcaption><img alt="Caption One." src="img/orange.jpg" title="Attribution One."/><dl><dt>Image owner:</dt><dd>Attribution One.</dd></dl></figure> 
<figure><figcaption>Caption Three.</figcaption><img alt="Caption Three." src="img/urban.jpg" title="Attribution Three."/><dl><dt>Image owner:</dt><dd>Attribution Three.</dd></dl></figure> 
<figure><figcaption>Caption Five.</figcaption><img alt="Caption Five." src="img/tomy.jpg" title="Attribution Five."/><dl><dt>Image owner:</dt><dd>Attribution Five.</dd></dl></figure> 

私は次の行をヤンクした場合、私はすべての5つの要素を取得します。誰かが間違ってやっていることについて何か悩んでいるのですか?

new_gallery_elem.insert(1, gallery_elem) 

答えて

0

だから、いくつかの実験の後、私は場合、私は私がリストに必要な要素を保存して、一覧からではなく、それは私の問題を解決住んでスープを編集しようとし、それらを取得したことがわかりました。

オブジェクトを作成して保存したら、以前作成してスープに挿入した親要素にそれらを追加できます。

私は、他の誰かのために早漏を解決することを願っています...

関連する問題