BeautifulSoup - 获取无 HTML 内容的简单方法 [英] BeautifulSoup - easy way to to obtain HTML-free contents

查看:27
本文介绍了BeautifulSoup - 获取无 HTML 内容的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码查找页面中所有有趣的链接:

I'm using this code to find all interesting links in a page:

soup.findAll('a', href=re.compile('^notizia.php?idn=d+'))

而且它的工作做得很好.不幸的是,在 a 标签内有很多嵌套标签,比如 fontb 和不同的东西......我想得到只是文本内容,没有任何其他 html 标签.

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.

链接示例:

<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

在文档中它说在 findAll 方法中使用 text=True ,但它会忽略我的正则表达式.为什么?我该如何解决?

In the documentation it says to use text=True in findAll method, but it will ignore my regex. Why? How can I solve that?

推荐答案

我用过这个:

def textOf(soup):
    return u''.join(soup.findAll(text=True))

所以...

texts = [textOf(n) for n in soup.findAll('a', href=re.compile('^notizia.php?idn=d+'))]

这篇关于BeautifulSoup - 获取无 HTML 内容的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆