【问题标题】:Modify html file (Find and replace href url and save it)修改html文件(查找并替换href url并保存)
【发布时间】:2019-10-06 18:39:38
【问题描述】:

编辑1:

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

我有一个 html 文件,我想为其他人更改一些 href url 并将其再次保存为 html 文件。我的目标是,当我打开 html 文件并单击链接时,它会将我带到内部文件夹而不是 Internet url(原始 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))

有什么想法吗?

【问题讨论】:

    标签: python html replace href


    【解决方案1】:

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

    我会制作“original_link1”等正则表达式,以便您轻松匹配。

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

    【讨论】:

    • 我已经尝试过该解决方案,并且出现了 TypeError: 'NoneType' object is not callable。我将编辑我的代码,向您展示我是如何做到的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多