详细了解如何导航through the parse tree in BeautifulSoup
。解析树已得到tags
和NavigableStrings
(因为这是一个文本)。一个例子
from BeautifulSoup import BeautifulSoup
doc = ['<html><head><title>Page title</title></head>',
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
'<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
'</html>']
soup = BeautifulSoup(''.join(doc))
print soup.prettify()
# <html>
# <head>
# <title>
# Page title
# </title>
# </head>
# <body>
# <p id="firstpara" align="center">
# This is paragraph
# <b>
# one
# </b>
# .
# </p>
# <p id="secondpara" align="blah">
# This is paragraph
# <b>
# two
# </b>
# .
# </p>
# </body>
# </html>
要下移你有contents
和string
解析树。
-
内容是标签的有序列表和NavigableString对象包含在一个页面元素中
-
如果一个标签只有一个子节点,该子节点是字符串, 子节点可用作tag.string,以及 tag.contents [0]
针对上述情况,也就是说,你可以得到
soup.b.string
# u'one'
soup.b.contents[0]
# u'one'
对于几个孩子节点,你可以有例如
pTag = soup.p
pTag.contents
# [u'This is paragraph ', <b>one</b>, u'.']
所以在这里你可以与contents
玩,获取你想要的索引的内容。
你也可以迭代一个标签,这是一个快捷方式。例如,
for i in soup.body:
print i
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>
这会返回'u'\ n评论\ nText \ nsomething \ n这是我的文本\ n别的\ n''或'u'a commentTextsomethingThis是我的文本\'其他'\',其中有更多的文本比需要。 –
@CristianCiupitu:当然,你是对的,在这里没有注意。更新。 –
这是唯一的解决方案,它不依赖于文本与特定其他文本的顺序或位置关系,而是从指定的标签/元素中提取所有文本,同时忽略子标签/元素的文本(或其他内容)。谢谢!这是尴尬的,但它的工作和解决我的问题(我不是OP,但有类似的需求)。 – geewiz