gpt4 book ai didi

python - 将html解析为文本并在python中保留链接

转载 作者:行者123 更新时间:2023-12-01 00:47:27 25 4
gpt4 key购买 nike

我需要将 html 解析为文本,但需要保留超链接。
我正在使用漂亮的肥皂(bs4),但 get_text() 仅获取文本并忽略任何 href。
示例:

<a href="http://example.com/">Example</a>

用bs4解析为:

Example

我需要它是这样的:

Example <http://example.com/>

最佳答案

您还需要获取 a 标记的 href 属性 (a_tag['href']):

In [16]: text = '<a href="http://example.com/">Example</a>'

In [17]: soup = BeautifulSoup(text, 'lxml')

In [18]: a_tag = soup.select_one('a')

In [19]: '{} <{}>'.format(a_tag.text, a_tag['href'])
Out[19]: 'Example <http://example.com/>'

关于python - 将html解析为文本并在python中保留链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56843163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com