我正在尝试<p>使用BeautifulSoup 从网页中的元素中删除所有内部html .有内部标签,但我不在乎,我只想获得内部文本.
例如,对于:
<p>Red</p>
<p><i>Blue</i></p>
<p>Yellow</p>
<p>Light <b>green</b></p>
Run Code Online (Sandbox Code Playgroud)
我怎样才能提取:
Red
Blue
Yellow
Light green
Run Code Online (Sandbox Code Playgroud)
我既不需.string也不.contents[0]需要.也不是.extract(),因为我不想提前指定内部标签 - 我想处理任何可能发生的事情.
BeautifulSoup中是否有'just get the visible HTML'类型的方法?
---- ------ UPDATE
在建议上,尝试:
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
Run Code Online (Sandbox Code Playgroud)
但这没有帮助 - 它打印出来:
0Red
1
2Blue
3
4Yellow
5
6Light
7green
8
Run Code Online (Sandbox Code Playgroud) 我刚开始学习Ruby.非常酷的语言,喜欢它很多.
我正在使用非常方便的Hpricot HTML解析器.
我要做的是从页面中获取所有文本,不包括HTML标记.
例:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Data Protection Checks</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
This is what I want to grab.
</div>
<p>
I also want to grab this text
</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我基本上只想抓取文本,所以最终得到一个像这样的字符串:
"这就是我想要抓住的.我也想抓住这个文字"
这样做的最佳方法是什么?
干杯
EEF
我在Mac OS X 10.6.8上的Python 2.7.3中运行以下代码.
import StringIO
from lxml import etree
f = open('./foo', 'r')
doc = ""
while 1:
line = f.readline()
doc += line
if line == "":
break
tree = etree.parse(StringIO.StringIO(doc), etree.HTMLParser())
r = tree.xpath('//foo')
for i in r:
for j in i.iter():
print j.tag, j.text
Run Code Online (Sandbox Code Playgroud)
文件foo包含
<foo> AAA <bar> BBB </bar> XXX </foo>
Run Code Online (Sandbox Code Playgroud)
输出是
foo AAA
bar BBB
Run Code Online (Sandbox Code Playgroud)
为什么我没有收到文字XXX?我该如何访问它?
谢谢