【问题标题】:Modify all local links in html file修改html文件中的所有本地链接
【发布时间】:2019-09-15 20:28:30
【问题描述】:

我想从下面的 html 页面更改链接:

//html
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>
        <p>this is a simple text in html file</p>
        <a href="https://google.com">Google</a>
        <a href="/frontend/login/">Login</a>
        <a href="/something/work/">Something</a>
    </body>
 </html>



//Result
    <html>
        <head>
            <title>Hello</title>
        </head>
        <body>
            <p>this is a simple text in html file</p>
            <a href="https://google.com">Google</a>
            <a href="/more/frontend/login/part/">Login</a>
            <a href="/more/something/work/extra/">Something</a>
        </body>
     </html>

那么如何将 html 更改为 result 并使用 python 将其保存为 html 呢?

【问题讨论】:

标签: python regex python-3.x beautifulsoup


【解决方案1】:

嗯,通过Regex 执行此操作非常简单。

使用href="\/([^"]*) 作为模式,href="\/more\/\1additional 作为替换。

看看这里:

https://regex101.com/r/7ACBFY/2


之前的“50% 尝试”(对不起,我错过了你的第二部分):

https://regex101.com/r/7ACBFY/1

【讨论】:

  • 谢谢你解决了 50%。我想在第一部分添加更多内容,并在链接末尾添加更多文本,如下所示:/more/something-previously-exists/extra/
  • 您的正则表达式 href="\/([^"]*) 可能包含无效链接
  • 什么意思?
【解决方案2】:

如果您将 html 文件存储为字符串(例如html),那么您可以进行简单的替换:

result = html.replace('<a href="/', '<a href="/more/')

【讨论】:

  • 链接不为空。我可能包含一些以前的数据。我想用以前的值添加更多。
【解决方案3】:

我自己解决了。但我认为这可以帮助很多人。这就是为什么我要回答我的问题并将其公开发布

谢谢Nicolas。他的 30-50% 解决方案对我的完整解决方案帮助很大。

import re

regex = r"href=\"\/"

test_str = ("<html>\n"
    "    <head>\n"
    "        <title>Hello</title>\n"
    "    </head>\n"
    "    <body>\n"
    "        <p>this is a simple text in html file</p>\n"
    "        <a href=\"https://google.com\">Google</a>\n"
    "        <a href=\"/front-end/login/\">Login</a>\n"
    "        <a href=\"/something/work/\">Something</a>\n"
    "    </body>\n"
    " </html>")

subst = "href=\"/more/"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

subst2 = "\\1hello/"
regex2 = r"(href=\"/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)"
result2 = re.sub(regex2, subst2, result, 0, re.MULTILINE)

if result2:
    print (result2)

writtingtofile = open("solution.html","w")
writtingtofile.write(result2)
writtingtofile.close()

输出:

【讨论】:

  • 干得好。抱歉,我没有注意到你的第二个附加任期。如果你想简化你的解决方案,看看这个(我也会编辑我的答案):regex101.com/r/7ACBFY/2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2019-11-26
相关资源
最近更新 更多