以下代码用于从html中获取连续的文本段落。
文本项由结构标签(如
例如,
我不确定这是否清楚... 如果不清楚,请告诉我。
编辑:我遍历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内容。也许我没有完全理解你的问题,但这样做不就解决了你的问题吗? - Oliver W.<br>
、<p>
等标签。我知道soup.get_text()
方法,但我不确定如何将其应用到我特定的开始和结束标签约束条件中(请参见我原始问题的编辑)。 - wrkyle<!-- Begin -->
,结束标签也是一个注释标签<!-- End -->
。我想要这两个注释标签之间的所有文本。如果有换行或者断行,只要保留完整的句子和单词,我就可以用空格替换它们。 - wrkyle