在文本中查找链接并替换为"a"标记



我有一个部分好的HTML,我需要创建超链接,如:

Superotto: risorse audiovisve per superare i pregiudizi e celebrarel 'otto marzo,《Indire Informa》,2021年3月5日,https://www.indire.it/2021/03/05/superotto-risorse-audiovisive-per-superare-i-pregiudizi-e-celebrare-lotto-marzo/;Sezione Superotto进来https://piccolescuole.indire.it/iniziative/la-scuola-allo-schermo/superotto .

必须变成:

Superotto: risorse audiovisve per superare i pregiudizi e celebrarel 'otto marzo,《Indire Informa》,5 marzo 2021,

Beautifulsoup似乎不能很好地找到http,所以我将这个正则表达式与纯python findall一起使用,但我无法替换或撰写文本。现在我写:

links = re.findall(r"(http|ftp|https://)([w_-]+(?:(?:.[w_-]+)+))([w.,@?^=%&:/~+#-]*[w@?^=%&/~+#-])", str(soup))
link_to_replace = []
for l in links:
link = ''.join(l)
if link in soup.find("body").text:
good_link = "<a href="+link+">"+link+"</a>"
fixed_text = soup.replace(link, good_link)
soup.replace_with(fixed_text)

我在最后两行尝试了多种解决方案(这只是一个),没有一个工作。

可能如下所示,我首先确定相关的锚元素并除去除href之外的任何其他属性,然后用href html

替换href链接
import re
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('https://rivista.clionet.it/vol5/giorgi-zoppi-la-ricerca-indire-tra-uso-didattico-del-patrimonio-storico-culturale-e-promozione-delle-buone-pratiche/')
soup = bs(r.text, 'lxml')
item = soup.select_one('p:has(a[id="ft-note-16"])')
text = item.text
for tag in item.select('a:not([id])'):
href = tag['href']
tag.attrs = {'href': href}
text = re.sub(href, str(tag), text)
text = re.sub(item.a.text, '', text).strip()
print(text)

最新更新