如何在树中插入新块?

使用 Beautifulsoup,我需要读取 KML 文件,并在包含 LineString 部分的所有地标中插入一个新块。


这是 KML 文件:


<?xml version="1.0" encoding="utf-8"?>

<kml xmlns="http://www.opengis.net/kml/2.2">

  <Document>

    <name>Document.kml</name>

    <Placemark>

      <name>My track</name>

      <LineString>

        <coordinates>-0.376291,43.296237,199.75

        -0.377381,43.29405</coordinates>

      </LineString>

    </Placemark>

  </Document>

</kml>

以下不起作用:


from bs4 import BeautifulSoup as Soup


with open('input.kml') as data:

    kml_soup = Soup(data, 'lxml-xml') # Parse as XML


placemarks = kml_soup.find_all('Placemark')

for pm in placemarks:

    if pm.find('LineString'):

        print("LS found")

        

        #How to insert new elements before LineString?

        #<Style><LineStyle><width>3</width></LineStyle></Style>

        style = kml_soup.new_tag("Style")

        style.string = "<LineStyle><width>3</width></LineStyle>"

        

        #AttributeError: 'NoneType' object has no attribute 'insert_before'

        pm.string.insert_before(style)


www说
浏览 119回答 1
1回答

蝴蝶不菲

您可能使用了错误的对象。尝试以下操作。placemarks = kml_soup.find_all('Placemark')for pm in placemarks:&nbsp; &nbsp; LineString = pm.find('LineString')&nbsp; &nbsp; if LineString:&nbsp; &nbsp; &nbsp; &nbsp; print("LS found")&nbsp; &nbsp; &nbsp; &nbsp; style = kml_soup.new_tag("Style")&nbsp; &nbsp; &nbsp; &nbsp; style.string = "<LineStyle><width>3</width></LineStyle>"&nbsp; &nbsp; &nbsp; &nbsp; LineString.insert_before(style) # Use LineString这是另一个解决方案。from simplified_scrapy import SimplifiedDoc,utilshtml = utils.getFileContent('input.kml')doc = SimplifiedDoc(html)placemarks = doc.selects('Placemark')for pm in placemarks:&nbsp; &nbsp; LineString = pm.select('LineString')&nbsp; &nbsp; if LineString:&nbsp; &nbsp; &nbsp; &nbsp; print("LS found")&nbsp; &nbsp; &nbsp; &nbsp; style = "<Style><LineStyle><width>3</width></LineStyle></Style>\n"+" "*6&nbsp; &nbsp; &nbsp; &nbsp; LineString.insertBefore(style)# print (doc.html)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python