查找并将每个引用附加到html链接Python

2024-04-29 13:39:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从Wikipedia获得的HTML文件,希望找到页面上的每个链接,例如/wiki/Absinthe,并将其替换为当前添加到前面的目录,例如/home/fergus/wikiget/wiki/Absinthe,因此:

<a href="/wiki/Absinthe">Absinthe</a>

变成:

^{pr2}$

整个文件都是这样。在

你有什么想法吗?我很乐意使用beauthulsoup或Regex!在


Tags: 文件目录home链接htmlwiki页面wikipedia
3条回答

如果这真的是你要做的,你可以用sed和它的-i选项来重写文件:

sed -e 's,href="/wiki,href="/home/fergus/wikiget/wiki,' wiki-file.html

但是,这里有一个使用可爱的lxmlAPI的Python解决方案,以防您需要执行更复杂的操作,或者可能有格式错误的HTML等:

^{pr2}$

注意,lxml对于这类任务可能比BeautifulSoup更好,因为BeautifulSoup的作者给出了reasons。在

这是使用re模块的解决方案:

#!/usr/bin/env python
import re

open('output.html', 'w').write(re.sub('href="http://en.wikipedia.org', 'href="/home/fergus/wikiget/wiki/Absinthe', open('file.html').read()))

这是另一个没有使用re的方法:

^{pr2}$

可以使用函数re.sub公司公司名称:

def match(m):
    return '<a href="/home/fergus/wikiget' + m.group(1) + '">'

r = re.compile(r'<a\shref="([^"]+)">')
r.sub(match, yourtext)

例如:

^{pr2}$

相关问题 更多 >