栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

美丽的汤-获取所有文本,但保留链接html?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

美丽的汤-获取所有文本,但保留链接html?

解决此问题的一种可能方法

a
是在打印出元素文本时对元素进行一些特殊处理。

您可以通过重写

_all_strings()
方法并返回
a
后代元素的字符串表示形式并跳过
a
元素内的可导航字符串来实现。遵循以下原则:

from bs4 import BeautifulSoup, NavigableString, CData, Tagclass MyBeautifulSoup(BeautifulSoup):    def _all_strings(self, strip=False, types=(NavigableString, CData)):        for descendant in self.descendants: # return "a" string representation if we encounter it if isinstance(descendant, Tag) and descendant.name == 'a':     yield str(descendant) # skip an inner text node inside "a" if isinstance(descendant, NavigableString) and descendant.parent.name == 'a':     continue # default behavior if (     (types is None and not isinstance(descendant, NavigableString))     or     (types is not None and type(descendant) not in types)):     continue if strip:     descendant = descendant.strip()     if len(descendant) == 0:         continue yield descendant

演示:

In [1]: data = """   ...: <td>   ...:     <font><span>Hello</span><span>World</span></font><br>   ...:     <span>Foo Bar <span>Baz</span></span><br>   ...:     <span>Example link: <a href="https://google.com" target="_blank" >Google</a></span>   ...: </td>   ...: """In [2]: soup = MyBeautifulSoup(data, "lxml")In [3]: print(soup.get_text())HelloWorldFoo Bar BazExample link: <a href="https://google.com"  target="_blank">Google</a>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/625826.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号