2012-08-28 11 views
12

Estoy escribiendo un script que edita un archivo XML con BeautifulStoneSoup, pero la biblioteca convierte todas las etiquetas en minúsculas. ¿Hay una opción para conservar el caso?¿Cómo mantener las etiquetas sensibles a mayúsculas y minúsculas en BeautifulSoup.BeautifulStoneSoup?

import BeautifulSoup  
xml = "<TestTag>a string</TestTag>"  
soup = BeautifulSoup.BeautifulStoneSoup(xml, markupMassage=False)  
print soup.prettify() # or soup.renderContents() 
#prints 
>>> <testtag>a string</testtag> 
#instead of the expected 
>>> <TestTag>a string</TestTag> 

Respuesta

15

Usted podría utilizar Beautiful Soup 4, de la siguiente manera (se requiere la biblioteca XML lxml):

In [10]: from bs4 import BeautifulSoup 

In [11]: xml = "<TestTag>a string</TestTag>" 

In [12]: soup = BeautifulSoup(xml, "xml") 

In [13]: print soup 
<?xml version="1.0" encoding="utf-8"?> 
<TestTag>a string</TestTag> 

In [14]: 
+1

Gracias, hizo la actualización y funciona muy bien. Para futuros lectores: ejecute 'pip install BeautifulSoup4' no' pip install beautifulsoup --upgrade' – TankorSmash

+1

Vale la pena mencionar que requiere la librería 'xml', no' lxml', que es lo que recomienda beautifulsoup si lo ejecuta sin ninguna especificación. 'lxml' no mantiene el caso. –

+0

@KeithSmiley: Sí, cuando se usa 'soup = BeautifulSoup (xml," lxml ")', se usa el analizador HTML de lxml. Ver http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser. – mzjn

Cuestiones relacionadas