编辑1:
我在我原来的代码中发现了一个错误,这给了我输入错误。答案是:BeautifulSoup - modifying all links in a piece of HTML?。代码正在运行。你知道吗
我有一个html文件,我想更改一些其他的href url,并再次保存为html文件。我的目标是,当我打开html文件并单击一个链接时,它会将我带到一个内部文件夹,而不是一个internet url(原始的)。你知道吗
我的意思是,我想把这个:<a href="http://www.somelink.com">
转换成:<a href="C:/myFolder/myFile.html">
。你知道吗
我试图用bs4打开文件并使用replace函数,但是我得到了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'属性,如果它们与dict中的匹配,根据需要替换。你知道吗
我会制作'original\u link1'等regexp,这样你就可以很容易地匹配了。你知道吗
碰巧,我相信你的问题已经回答了,请看BeautifulSoup - modifying all links in a piece of HTML?
相关问题 更多 >
编程相关推荐