开发者

BeautifulSoup - easy way to to obtain HTML-free contents

开发者 https://www.devze.com 2022-12-12 06:30 出处:网络
I\'m using this code to find all interestinglinks in a page: soup.findAll(\'a\', href=re.compile(\'^notizia.php\\?idn=\\d+\'))

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 studen开发者_JAVA技巧ti 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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消