2010-06-07 4 views
1

J'essaie de traduire une page html en ligne en texte.Comment empêcher BeautifulSoup de supprimer des lignes

J'ai un problème avec cette structure:

<div align="justify"><b>Available in 
<a href="http://www.example.com.be/book.php?number=1"> 
French</a> and 
<a href="http://www.example.com.be/book.php?number=5"> 
English</a>. 
</div> 

Voici sa représentation sous forme de chaîne de python:

'<div align="justify"><b>Available in \r\n<a href="http://www.example.com.be/book.php?number=1">\r\nFrench</a>; \r\n<a href="http://www.example.com.be/book.php?number=5">\r\nEnglish</a>.\r\n</div>' 

Lorsque vous utilisez:

html_content = get_html_div_from_above() 
para = BeautifulSoup(html_content) 
txt = para.text 

BeautifulSoup traduit (en la variable 'txt'):

u'Available inFrenchandEnglish.' 

Il supprime probablement chaque ligne de la chaîne html d'origine.

Avez-vous une solution propre à ce problème?

Merci.

Répondre

2

J'ai finalement obtenu une bonne solution:

def clean_line(line): 
    return re.sub(r'[ ]{2,}', ' ', re.sub(r'[\r\n]', '', line)) 

html_content = get_html_div_from_above() 
para = BeautifulSoup(html_content) 
''.join([clean_line(line) for line in para.findAll(text=True)]) 

qui sort:

u'Available in French and English. ' 
1

Je solution obtenu une:

html_content = get_html_div_from_above() 
para = BeautifulSoup(html_content) 
txt = para.getText(separator=' ') 

Mais ce n'est pas optimal car il met des espaces entre chaque tag:

u'Available in French and English . ' 

Notez l'espace avant le point.

Questions connexes