使用 BeautifulSoup 提取嵌入 link 的文本

Extract text with embedded link using BeautifulSoup

我正在尝试提取包含 link 的网络文章的文本作为文本的一部分。这方面的一个例子是:

<p>Here is some text with <a href="https://www.example.com"> this part as a link</a>
which we will look at.</p>

我试过使用

table.findAll('p', text = True)

数据,但此命令忽略所有包含 url 的 'p' 标签(也就是说,它不会选取第一个块中的示例)。我的问题是,如何从 'p' 标签中提取文本,同时还包括嵌入的 links 以及如何删除 link 的 url 并只保留'this part as a link' 突出显示的文本?非常感谢任何帮助。

基本上是这样的:

>>> import bs4
>>> HTML = '''\
... <p>Here is some text with <a href="https://www.example.com"> this part as a link</a>
... which we will look at.</p>'''
>>> soup = bs4.BeautifulSoup(HTML, 'lxml')
>>> [p.text for p in soup.findAll('p')]
['Here is some text with  this part as a link\nwhich we will look at.']

当然,您很可能希望替换新行和多余的空格。