【问题标题】:Formatting an HTML tag格式化 HTML 标签
【发布时间】:2018-04-14 02:21:29
【问题描述】:

我有一个如下所示的 HTML 页面:

<html>
   <head>
     <title>TEST</title>
   </head>
   <body>
     <p>Testing</p>
     <iframe src="{}" width="500" height="500"></iframe>
   </body>
</html>

我需要用网站链接格式化&lt;iframe src="{} 部分,例如:&lt;iframe src="https://google.com"

我的问题是,如何使用 python 内置库(或外部库)格式化 HTML 字符串中的标签?这是我的尝试:

retval = ""
for item in HTML_page.readlines():
    if "<iframe src" in item:
        item = item.format(LINK)
        retval += item 
    else:
        retval += item
    return retval

这可行,但不是很漂亮。有没有办法让我更像 python?

【问题讨论】:

  • 所以你基本上想动态改变 iframe 的 src ?
  • @RohitasBehera 是的,我不知道要使用的措辞,抱歉。但这基本上是我想要的。
  • 这可能是你要找的stackoverflow.com/questions/3945750/…
  • 另外,你能发布你的尝试吗?我们可以帮你解决
  • @yklsga 我还在努力。我发布了我的尝试示例

标签: python html python-2.7 format


【解决方案1】:

如果 HTML 代码如下所示:

<html>
   <head>
     <title>TEST</title>
   </head>
   <body>
     <p>Foo</p>
     <iframe src="{}" width="500" height="500"></iframe>
     <p>Bar</p>
     <iframe src="{}" width="500" height="500"></iframe>
   </body>
</html>

然后您可以在所有链接上简单地使用str.format

URLS = (
    "https://www.example.com/",
    "https://www.example.com/"
)

html_code = """<html>
   <head>
     <title>TEST</title>
   </head>
   <body>
     <p>Foo</p>
     <iframe src="{}" width="500" height="500"></iframe>
     <p>Bar</p>
     <iframe src="{}" width="500" height="500"></iframe>
  </body>
</html>
"""
html_code = html_code.format(*URLS)

【讨论】:

  • 它是从 HTML 文件中读取的,这就是我在示例中所做的。
【解决方案2】:

使用beautifulsoup,你可以这样做

from bs4 import BeautifulSoup

url = 'insert your url here'

with open('file.html','r') as f:
    text = f.read()

soup = BeautifulSoup(text,'html.parser')

soup.body.iframe['src'] = url

with open('file.html','w') as f:
    f.write(str(soup))

无需使用任何第三方库,因为您已经获得了它。我删除了一些语句并修改了代码

retval = ""
HTML_page = open('file.html','r')
LINK = 'google.com'

for item in HTML_page.readlines():
    if "<iframe src" in item:
        item = item.format(LINK)
    retval += item

HTML_page.close()
print(retval)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    相关资源
    最近更新 更多