问题
I'm using this code to find all interesting links in a page:
soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))
And it does its job pretty well. Unfortunately inside that a tag there are a lot of nested tags, like font, b and different things... I'd like to get just the text content, without any other html tag.
Example of 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>
Of course it's ugly (and the markup is not always the same!) and I'd like to get:
03-11-2009: CCS Ingegneria Elettronica-Sportello studenti ed orientamento
In the documentation it says to use text=True
in findAll method, but it will ignore my regex. Why? How can I solve that?
回答1:
I've used this:
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+'))]
回答2:
Interested in a pyparsing take on the 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
This is actually pretty impervious to HTML vagaries, as it factors in presence/absence of attributes, upper/lower case, and so on.
来源:https://stackoverflow.com/questions/1752662/beautifulsoup-easy-way-to-to-obtain-html-free-contents