Question

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:&nbsp;&nbsp;<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?

Was it helpful?

Solution

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+'))]

OTHER TIPS

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:&nbsp;&nbsp;<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("&nbsp;"," ")
    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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top