gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:01:08 26 4
gpt4 key购买 nike

我有一个从维基百科获得的 HTML 文件,我想找到页面上的每个链接,例如 /wiki/Absinthe 并将其替换为添加到前面的当前目录,例如 /home/fergus/wikiget/wiki/Absinthe 所以:

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

变成:

<a href="/home/fergus/wikiget/wiki/Absinthe">Absinthe</a>

这贯穿整个文档。

你有什么想法吗?我很高兴使用 BeautifulSoup 或 Regex!

最佳答案

如果这真的是您要做的全部,您可以使用 sed 及其 -i 选项来就地重写文件:

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

但是,这里有一个使用可爱的 lxml 的 Python 解决方案API,以防您需要做任何更复杂的事情,或者您的 HTML 格式可能不正确等:

from lxml import etree
import re

parser = etree.HTMLParser()

with open("wiki-file.html") as fp:
tree = etree.parse(fp, parser)

for e in tree.xpath("//a[@href]"):
link = e.attrib['href']
if re.search('^/wiki',link):
e.attrib['href'] = '/home/fergus/wikiget'+link

# Or you can just specify the same filename to overwrite it:
with open("wiki-file-rewritten.html","w") as fp:
fp.write(etree.tostring(tree))

请注意,对于 reasons 而言,lxml 现在对于此类任务可能是比 BeautifulSoup 更好的选择。由 BeautifulSoup 的作者提供。

关于python - 查找每个引用并将其附加到 html 链接 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5217760/

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