【问题标题】:How to add a url into html file如何将url添加到html文件中
【发布时间】:2026-02-01 04:00:02
【问题描述】:
<html>
<body>

<h2>HTML Iframes</h2>
<p>You can use the height and width attributes to specify the size of the    iframe:</p>

<iframe src="https://www.google.com/maps/embed/v1/place?key=AIzaSyAPi0wzs7IlNc4nlL3atU7iCd-A9QXfuHs&q=4.5596%2C-76.2801&zoom=18&maptype=satellite" height="200" width="300"></iframe>

</body>
</html>

所以在我的计算机上创建了这个 html 文件,现在我需要将 src 之后的内容更改为新字符串,例如 -

https://www.google.com/maps/embed/v1/place?key=AIzaSyAPi0wzs7IlNc4nlL3atU7iCd-A9QXfuHs&q=25.5596%2C-7.2801&zoom=18&maptype=satellite

那么如何在 src= 之后将该示例行添加到 html 文件中?

【问题讨论】:

  • 所以您问如何更改iframe 标签的src
  • 是的,我的 url 数据每天都在变化,我需要保持 src 更新
  • 您可能必须手动更改它
  • @AlexShakhnovskiy 您可以使用BeautifulSoup 获取 iframe 标签并更改 src。
  • 嗯,我想过,但它每隔几个小时左右就会改变一次,所以每当我运行代码时,我都必须更新它。这应该是可能的,但我知道如何实现它

标签: python html iframe


【解决方案1】:
from bs4 import BeautifulSoup

htmlstr = '''
<html>
<body>

<h2>HTML Iframes</h2>
<p>You can use the height and width attributes to specify the size of the    iframe:</p>

<iframe src="https://www.google.com/maps/embed/v1/place?key=AIzaSyAPi0wzs7IlNc4nlL3atU7iCd-A9QXfuHs&q=4.5596%2C-76.2801&zoom=18&maptype=satellite" height="200" width="300"></iframe>

</body>
</html>
'''

soup = BeautifulSoup(htmlstr)

iframe = soup.find('iframe')
iframe["src"] = "test"
print(soup)

这应该是您正在寻找的解决方案。将 iframe["src"] = "test" 替换为您要提供的链接并将结果保存回 html 文件。

【讨论】:

  • 谢谢,但我尝试运行它并从 bs4 import BeautifulSoup html = open('api.htm').read() soup = BeautifulSoup(html) iframe = soup.find('iframe' ) iframe["src"] = "test" with open("output_api.html", "w") as file: file.write(soup) print(soup) TypeError: 'NoneType' object does not support item assignment on line 8
  • 我认为它没有找到 iframe 标签,因此 iframe["src"] = "test" 失败。您是否已单步执行您的代码并检查 `soup = BeautifulSoup(html)` 是否为您提供了正确的页面?
  • @AlexShakhnovskiy soup 变量真的包含iframe 标签吗?
  • @AlexShakhnovskiy 现在什么不起作用。我在python 3.7.2 上发布的代码非常适合我,我不想说脾气暴躁,但你需要让自己更清楚,我才能为你提供帮助。
  • 好的,nonetype 错误仍然存​​在,甚至知道它确实打印了所有信息的汤 1 次,然后它停止打印任何东西(这是我现在的位置)