【发布时间】:2016-05-30 02:37:46
【问题描述】:
以下代码用于从 html 中抓取连续的文本段。
for text in soup.find_all_next(text=True):
if isinstance(text, Comment):
# We found a comment, ignore
continue
if not text.strip():
# We found a blank text, ignore
continue
# Whatever is left must be good
print(text)
文本项由<div> 或<br> 等结构标签以及<em> 和<strong> 等格式标签分解。这给我进一步解析文本带来了一些不便,我希望能够抓取连续的文本项,同时忽略文本内部的任何格式标记。
例如,soup.find_all_next(text=True) 将采用 html 代码 <div>This is <em>important</em> text</div> 并返回单个字符串 This is important text,而不是三个字符串 This is、important 和 text。
我不确定这是否清楚...如果不是,请告诉我。
编辑:我逐个文本项遍历 html 文本项的原因是,我只是在看到特定的“开始”注释标记并且停止后才开始遍历当我到达特定的“结束”评论标签时。在需要逐项遍历的情况下,是否有任何解决方案有效?我正在使用的完整代码如下。
soup = BeautifulSoup(page)
for instanceBegin in soup.find_all(text=isBeginText):
# We found a start comment, look at all text and comments:
for text in instanceBegin.find_all_next(text=True):
# We found a text or comment, examine it closely
if isEndText(text):
# We found the end comment, everybody out of the pool
break
if isinstance(text, Comment):
# We found a comment, ignore
continue
if not text.strip():
# We found a blank text, ignore
continue
# Whatever is left must be good
print(text)
如果传递给它们的字符串与我的开始或结束注释标签匹配,则 isBeginText(text) 和 isEndText(text) 这两个函数返回 true。
【问题讨论】:
-
如果您有两个嵌套的块级标签,您想如何处理?比如说
<div>A<p>B</p>C</div>。你想要什么?无论如何,我的看法是,您应该检查当前标签是否有任何后代。如果是这样,请(递归地)检查这些后代是否属于“格式化”类型(注意这是主观的:您认为em是其中之一,但不是br),如果是,请删除格式化标签,但保留内部 HTML。也许我没有完全理解你的问题,但这不能解决你的问题吗? -
是的,我听到了。实际上,除了保留基本句子结构之外,我不关心任何格式。我可以忽略
<br>、<p>等,只要保留句子(即,单词不会混在一起)。我知道soup.get_text()方法,但我不确定如何将其应用于我关于开始和结束标签的特定约束(请参阅我的原始问题的编辑)。 -
@OliverW。你打赌:开始标签是评论标签
<!-- Begin -->,结束标签也是评论标签<!-- End -->。我想要这两个评论标签之间的所有文本。如果有新行或中断,我很乐意将其替换为空格,只要它保留完整的句子和单词。
标签: python html python-3.x beautifulsoup bs4