BeautifulSoup - einfache Möglichkeit, Sie zu erhalten HTML-Inhalte kostenlos
-
20-09-2019 - |
Frage
Ich bin mit diesem code zu finden, alle interessante links in einer Seite:
soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))
Und es macht seinen job ziemlich gut.Leider innen, ein tag es gibt eine Menge von verschachtelten tags, wie schriftart, b und andere Dinge, die...Ich würde gerne nur den text, ohne jede andere html-Tags.
Beispiel-link:
<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>
Natürlich ist es hässlich ist (und das markup ist nicht immer das gleiche!) und ich möchte erhalten:
03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento
In der Dokumentation heißt es zu verwenden text=True
in der findAll-Methode, aber es wird ignoriert mein regex.Warum?Wie kann ich das lösen?
Lösung
Ich habe diese verwendet:
def textOf(soup):
return u''.join(soup.findAll(text=True))
So...
texts = [textOf(n) for n in soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))]
Andere Tipps
Interesse an einem pyparsing nehmen auf das problem?
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)
Prints:
03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento
Dies ist eigentlich ziemlich unempfindlich zu HTML Launen, wie es Faktoren in der Anwesenheit/Abwesenheit von Parametern wird groß - /Kleinschreibung, und so auf.