Изменить все локальные ссылки в HTML-файле - PullRequest
1 голос
/ 26 апреля 2019

Я хочу изменить ссылки со страницы 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 на результат и сохранить его как html с помощью python?

Ответы [ 3 ]

0 голосов
/ 26 апреля 2019

Если вы сохраняете html-файл в виде строки (например, html), вы можете выполнить простую замену:

result = html.replace('<a href="/', '<a href="/more/')
0 голосов
/ 26 апреля 2019

Я решил это самостоятельно. Но я думаю, что это может помочь многим людям. Поэтому я отвечаю на свой вопрос и оставляю его в открытом доступе

Спасибо Николас . Его 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()

Выход:

enter image description here

0 голосов
/ 26 апреля 2019

Что ж, сделать это через Regex действительно просто.

Используйте href="\/([^"]*) в качестве шаблона и href="\/more\/\1additional в качестве замены.

Посмотрите здесь:

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


Предыдущая «попытка 50%» (жаль, что я скучал по второй части):

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...