亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在樹中插入新塊?

如何在樹中插入新塊?

www說 2023-06-27 18:20:54
使用 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 Soupwith open('input.kml') as data:    kml_soup = Soup(data, 'lxml-xml') # Parse as XMLplacemarks = 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)
查看完整描述

1 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

您可能使用了錯誤的對象。嘗試以下操作。


placemarks = kml_soup.find_all('Placemark')

for pm in placemarks:

    LineString = pm.find('LineString')

    if LineString:

        print("LS found")

        style = kml_soup.new_tag("Style")

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

        LineString.insert_before(style) # Use LineString

這是另一個解決方案。


from simplified_scrapy import SimplifiedDoc,utils

html = utils.getFileContent('input.kml')

doc = SimplifiedDoc(html)

placemarks = doc.selects('Placemark')

for pm in placemarks:

    LineString = pm.select('LineString')

    if LineString:

        print("LS found")

        style = "<Style><LineStyle><width>3</width></LineStyle></Style>\n"+" "*6

        LineString.insertBefore(style)

# print (doc.html)


查看完整回答
反對 回復 2023-06-27
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號