Изменить URL с помощью BeautifulSoup - PullRequest
0 голосов
/ 31 мая 2019

Мне нужно изменить значения href ссылок в файле HTML, но по какой-то причине это не происходит.Вот часть, где я пытаюсь сделать это:

a['href'] = internal

Вот описание сценария

Этот сценарий создает список всех файлов .html в папке,Обратитесь к инженерам, указав соответствующий веб-URL (у меня есть другой скрипт, который загружает веб-страницы и создает локальные версии).Открывает каждый файл один за другим, находит URL-адреса, являющиеся внешними ссылками, и заменяет их локальными

import re
import os
from bs4 import BeautifulSoup

def replace_links(destination):
    files = []
    external_links = [] 
    #r = root, d = directories, f = files
    for r, d, f in os.walk(destination):
        for file in f:
            if '.html' in file:
                files.append(os.path.join(r, file))

    for f in files:
        external_links.append(reverse_eng_url(f, destination))

    html(files, external_links)

def reverse_eng_url(origin_url, destination):
    return origin_url.replace(destination, "").replace("-","/").replace("\\","/").replace("html", "aspx")

def html(files, external_links):
    for local in files:
        #open and read content of each file
        with open(local, "r") as f:
            contents = f.read()
            soup = BeautifulSoup(contents, "lxml")
            # find links in each file that contain external links and replace them with internal
            for internal, ext in zip(files, external_links):
                #print ext
                for a in soup.find_all("a", href=re.compile(ext)):
                    #print a
                    print(a['href']) 
                    print(internal)
                    #------------------------The problem is here
                    a['href'] = internal #a[href] is found, internal also exists as a value, but for some reason internal doesn't get assigned to a[href]
                    #___________________________________________


if __name__ == "__main__":
    replace_links("C:\\Transition\\")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...