以下代码用于从 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>
or )和<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)
true 。isEndText(text)