如何使用 lxml.etree 添加多个子元素? (python)

How to add multiple SubElement using lxml.etree? (python)

我想用lxml.etree在一个主标签下写出几个子元素,多个子标签。

这是我用来写出我的标签的代码。

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'

您只需创建一次 Products 元素,并使用 Products 作为父元素创建多个 ProductName 元素,如下所示:

....
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)