修改html文件(查找并替换hrefurl并保存)

Modify html file (Find and replace href url and save it)

编辑 1:

我在我的原始代码中发现了一个错误,它给了我 typeError。所以答案在这里:BeautifulSoup - modifying all links in a piece of HTML?。代码现在可以正常工作了。

我有一个 html 文件,我想为其他人更改一些 href url 并将其再次保存为 html 文件。我的目标是,当我打开 html 文件并单击 link 时,它会将我带到内部文件夹而不是互联网 url(原始文件夹)。

我的意思是,我想将这个:<a href="http://www.somelink.com"> 转换成这个:<a href="C:/myFolder/myFile.html">

我尝试用 bs4 打开文件并使用替换功能,但我得到 TypeError: 'NoneType' object is not callable

现在这是我的代码:


# Dict which relates the original links with my the ones to replace them

links_dict = { original_link1 : my_link1 , original_link2 : my_link2 } # and so on..

# Get a list of links to loop and find them into the html file

original_links = links_dict .keys() 

soup = BeautifulSoup(open(html_file), "html.parser",encoding="utf8")

# This part is where I am stuck, the theory is loop through 'original_links'
 and if any of those links is found, replace it with the one I have in 'links_dict'

for link in soup.find_all('a',href=True):
    if link['href'] in links_dict:
        link['href'] = link['href'].replace(link['href'],links_dict[link['href']]

with open("new_file.html", "w",encoding="utf8") as file:
    file.write(str(soup))

有什么想法吗?

一旦你有一些汤要处理,你应该寻找 'a' 元素,然后检查它们的 'href' 属性,如果它们与你的字典中的那些匹配,则根据需要替换。

我会制作 'original_link1' 等正则表达式,这样您就可以轻松匹配。

碰巧,我相信你的问题已经得到解答,请参阅BeautifulSoup - modifying all links in a piece of HTML?