如何在Python中干扰HTML链接字符串中的文本

1 投票
2 回答
2222 浏览
提问于 2025-04-16 14:20

我所在的公司使用上面的命令,从我们在地图上保存的数据列表中构建一个链接。

link=a % firstUpper(b)

这个命令生成的结果大概是这样的:

<a href="path/tomyhtml/foo.html">foo</a>

我想修改这个链接字符串,给它添加一个标题属性,这样它就变成了:

<a href="path/tomyhtml/foo.html" title="Some cool title">foo</a>

我想的办法是把标题加在第三个字符的位置,通常这个位置是一个空格,但我觉得这不是最优雅的解决方案。

2 个回答

2
s = '<a href="%s" title="%s">foo</a>'

print s % (href_string, title_string)

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

4

使用 BeautifulSoup

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('<a href="path/tomyhtml/foo.html">foo</a>')
soup.a["title"] = "Some cool title"

撰写回答