适用于您的特定示例的方法是:
from BeautifulSoup import BeautifulSoup
ht = '''
<div id="abc">
some long text goes <a href="/"> here </a> and hopefully it
will get picked up by the parser as content
</div>
'''
soup = BeautifulSoup(ht)
anchors = soup.findAll('a')
for a in anchors:
a.prevIoUsSibling.replaceWith(a.prevIoUsSibling + a.string)
results = soup.findAll(text=lambda(x): len(x) > 20)
print results
发出
$ python bs.py
[u'\n some long text goes here ', u' and hopefully it \n will get picked up by the parser as content\n']
当然,你可能需要采取多一点关怀,即,如果没有a.string
,或者a.prevIoUsSibling
是None
-你需要合适的if
语句来采取这种极端情况的照顾。但我希望这个总体思路能对您有所帮助。(事实上,你可能想_也_ 合并 @H_404_21@下一个 兄弟,如果它是一个字符串-与您的启发式不知道如何播放len(x) > 20
,但说,例如,你有两个9个字符的字符串与<a>
中间包含5个字符的字符串,也许您想将其作为“ 23个字符的字符串”使用呢?我不知道是因为我不理解您启发式搜索的动机)。
我想除了<a>
标签,您还希望删除其他标签,例如<b>
或<strong>
,也许<p>
和/或<br>
,等等…?我想这也取决于启发式技术背后的实际想法!