我正在尝试从 中删除所有内部 html<p>
使用 BeautifulSoup 的网页中的元素。有内部标签,但我不在乎,我只想获取内部文本。
例如,对于:
<p>Red</p>
<p><i>Blue</i></p>
<p>Yellow</p>
<p>Light <b>green</b></p>
我怎样才能提取:
Red
Blue
Yellow
Light green
Neither .string
nor .contents[0]
做我需要的。也没有.extract()
,因为我不想提前指定内部标签 - 我想处理任何可能发生的情况。
BeautifulSoup 中是否有“仅获取可见 HTML”类型的方法?
- - 更新 - - -
根据建议,尝试:
soup = BeautifulSoup(open("test.html"))
p_tags = soup.findAll('p',text=True)
for i, p_tag in enumerate(p_tags):
print str(i) + p_tag
但这并没有帮助 - 它打印出:
0Red
1
2Blue
3
4Yellow
5
6Light
7green
8
简短回答:soup.findAll(text=True)
这个已经回答过了,在 StackOverflow 上 https://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text并在BeautifulSoup 文档 http://www.crummy.com/software/BeautifulSoup/documentation.html#Advanced%20Topics.
UPDATE:
为了澄清这一点,一段工作代码:
>>> txt = """\
... <p>Red</p>
... <p><i>Blue</i></p>
... <p>Yellow</p>
... <p>Light <b>green</b></p>
... """
>>> import BeautifulSoup
>>> BeautifulSoup.__version__
'3.0.7a'
>>> soup = BeautifulSoup.BeautifulSoup(txt)
>>> for node in soup.findAll('p'):
... print ''.join(node.findAll(text=True))
Red
Blue
Yellow
Light green
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)