【发布时间】:2011-02-26 18:32:54
【问题描述】:
我正在尝试使用 BeautifulSoup 从网页中的 <p> 元素中抓取所有内部 html。有内部标签,但我不在乎,我只想获取内部文本。
例如,对于:
<p>Red</p>
<p><i>Blue</i></p>
<p>Yellow</p>
<p>Light <b>green</b></p>
如何提取:
Red
Blue
Yellow
Light green
.string 和 .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
【问题讨论】:
标签: python beautifulsoup