2017-05-20 13 views
0

lxml.etreeを使用して、いくつかのサブタグを持つ1つのプライマリタグの下に複数のSubElementsを書きたいと思います。lxml.etreeを使って複数のSubElementを追加するには?

これは、タグを書き込むために使用しているコードです。

def create_SubElement(_parent, _tag, attrib={}, _text=None, nsmap=None, **_extra): 
    result = ET.SubElement(_parent, _tag, attrib, nsmap, **_extra) 
    result.text = _text 
    return result 

これは複数のp_tagsを持つコードです。現在、上記

for key_products in primary_details: 
    try: 
     if 'Products' in key_products.h3.text: 
      for p_tag in key_products.find_all('p'): 
       products = create_SubElement(root, 'Products', _text=p_tag.text) 

     except: 
      continue 

print (ET.tostring(root, pretty_print=True)) 

コードは、この出力を生成します

'<root>\n 
    <Products>product name 1 </Products>\n 
    <Products>product name 2 </Products>\n 
    <Products>product name 3 </Products>\n 
    <Products>product name 4 </Products>\n 
    <Products>product name 5 </Products>\n 
</root>\n' 

所望の出力は、このようなものになるだろう:

'<root>\n 
    <Products> 
     <ProductName>product name 1 </ProductName>\n 
     <ProductName>product name 2 </ProductName>\n 
     <ProductName>product name 3 </ProductName>\n 
     <ProductName>product name 4 </ProductName>\n 
     <ProductName>product name 5 </ProductName>\n 
    <Products> 
</root>\n' 

答えて

1

あなたは一度だけProducts要素を作成し、複数を作成する必要がProductName要素がProductsを親として使用している場合は、次のようになります。

.... 
if 'Products' in key_products.h3.text: 
    # create Products element once: 
    products = create_SubElement(root, 'Products') 
    for p_tag in key_products.find_all('p'): 
     # create ProductName element using Products as parent 
     productName = create_SubElement(products, 'ProductName', _text=p_tag.text) 
+0

ProductNamesを持たない製品はどのように処理できますか?私は_text = NULL値を作成しようとしましたが、p_tagが<= 0であっても動作しませんでした。 NULLというタグを作成しようとしています。 –

関連する問題