Python Forum

Full Version: [SOLVED] [Beautifulsoup] Find if element exists, and edit/append?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I read BS's documentation, but can't figure out something very simple: Find if an element exists at a specific location in the tree; If it exists, change its text; If it doesn't, insert it right below the parent.

from bs4 import BeautifulSoup 

"""
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
  <name>
   EDIT ME
  </name>
 </Document>
</kml>
"""
soup = BeautifulSoup(open('input.kml', 'r'), 'xml')

#BAD name = soup.kml.Document.name
name = soup.select('kml > Document > name') 
if name:
	print("Found")
	name.string="New name" #no change !
	name.string.replace_with("New name") #Error
else:
	print("Not found")
	name = soup.new_tag("name")
	name.string = "New tag"

	#doc= soup.kml.Document
	#doc = soup.select('kml.Document')
	doc = soup.select('kml > Document') 
	doc.append(name) #No change !

print(soup.prettify())
Thank you.
If a tag tag doesn't exits it will give AttributeError,then catch this error and insert a new tag.
from bs4 import BeautifulSoup

"""
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
  <name>
   EDIT ME
  </name>
 </Document>
</kml>
"""

soup = BeautifulSoup(open('input.xml'), 'xml')
try:
    name = soup.select_one('kml > Document > name')
    name.string = 'hello'
except (AttributeError, NameError):
    doc = soup.find('Document')
    new_tag = soup.new_tag("car")
    new_tag.string = "Blue color"
    doc.append(new_tag)
>>> print(soup.prettify())
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
  <name>
   hello
  </name>
 </Document>
</kml>
if search eg for soup.select_one('kml > Document > name_99')
>>> print(soup.prettify())
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
  <name>
   EDIT ME
  </name>
  <car>
   Blue color
  </car>
 </Document>
</kml>
Thanks much.