BeautifulSoup - un moyen simple d'obtenir du contenu sans HTML
-
20-09-2019 - |
Question
J'utilise ce code pour trouver tous les liens intéressants dans une page :
soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))
Et il fait plutôt bien son travail.Malheureusement à l'intérieur de ça un tag il y a beaucoup de balises imbriquées, comme Police de caractère, b et différentes choses...J'aimerais obtenir uniquement le contenu du texte, sans aucune autre balise HTML.
Exemple de lien :
<A HREF="notizia.php?idn=1134" OnMouseOver="verde();" OnMouseOut="blu();"><FONT CLASS="v12"><B>03-11-2009: <font color=green>CCS Ingegneria Elettronica-Sportello studenti ed orientamento</B></FONT></A>
Bien sûr, c'est moche (et le balisage n'est pas toujours le même !) et j'aimerais obtenir :
03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento
Dans la documentation, il est dit d'utiliser text=True
dans la méthode findAll, mais elle ignorera mon regex.Pourquoi?Comment puis-je résoudre cela ?
La solution
J'ai utilisé ceci :
def textOf(soup):
return u''.join(soup.findAll(text=True))
Donc...
texts = [textOf(n) for n in soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))]
Autres conseils
Intéressé par une approche pyparsing du problème ?
from pyparsing import makeHTMLTags, SkipTo, anyOpenTag, anyCloseTag, ParseException
htmlsrc = """<A HREF="notizia.php?idn=1134" OnMouseOver="verde();" OnMouseOut="blu();"><FONT CLASS="v12"><B>03-11-2009: <font color=green>CCS Ingegneria Elettronica-Sportello studenti ed orientamento</B></FONT></A>"""
# create pattern to find interesting <A> tags
aStart,aEnd = makeHTMLTags("A")
def matchInterestingHrefsOnly(t):
if not t.href.startswith("notizia.php?"):
raise ParseException("not interested...")
aStart.setParseAction(matchInterestingHrefsOnly)
patt = aStart + SkipTo(aEnd)("body") + aEnd
# create pattern to strip HTML tags, and convert HTML entities
stripper = anyOpenTag.suppress() | anyCloseTag.suppress()
def stripTags(s):
s = stripper.transformString(s)
s = s.replace(" "," ")
return s
for match in patt.searchString(htmlsrc):
print stripTags(match.body)
Impressions :
03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento
Ceci est en fait assez imperméable aux caprices du HTML, car il prend en compte la présence/absence d'attributs, les majuscules/minuscules, etc.