【发布时间】: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))
有什么想法吗?
【问题讨论】: