You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python替换HTML中img标签src属性内的指定域名

解决方案

推荐使用BeautifulSoup库实现精准替换,不要使用正则表达式处理HTML,避免匹配到非预期内容。

第一步:安装依赖

pip install beautifulsoup4 lxml

如果不想安装额外的lxml解析库,也可以使用Python内置的html.parser作为解析器,无需额外安装。

第二步:完整实现代码

from bs4 import BeautifulSoup
from urllib.parse import urlparse, urlunparse

# 待处理的HTML字符串
html_str = """
<body>
    <img
        alt="Images may be two-dimensional, such as a photograph or screen display, or three-dimensional, such as a statue or hologram. They may be captured by optical devices – such as cameras, mirrors, lenses, telescopes, microscopes, etc. and natural objects and phenomena, such as the human eye or water."
        height="333"
        src="https://tvfcommunity-dev-ed--c.documentforce.com/servlet/rtaImage?eid=ka02v000001BOfL&amp;feoid=00N2v00000Rjh9i&amp;refid=0EM2v000002ijZG"
        width="500"
    />
    <br />
    Images may be two-dimensional, such as a photograph or screen display, or three-dimensional, such as a statue or hologram.
</body>
"""

# 解析HTML,用html.parser的话把lxml换成html.parser即可
soup = BeautifulSoup(html_str, 'lxml')

# 遍历所有img标签
for img in soup.find_all('img'):
    # 跳过无src属性的标签
    if not img.get('src'):
        continue
    src = img['src']
    parsed_src = urlparse(src)
    # 仅匹配目标域名的src
    if parsed_src.netloc == 'tvfcommunity-dev-ed--c.documentforce.com':
        # 替换域名
        new_src = urlunparse(parsed_src._replace(netloc='globalcommunity.networks.com'))
        img['src'] = new_src

# 获得处理后的HTML字符串
result = str(soup)
print(result)

方案特性

  • 仅修改img标签的src属性,普通文本、a标签、iframe等其他标签的内容和属性完全不受影响
  • 使用URL解析工具精准匹配域名,避免字符串替换时的误匹配问题
  • 兼容各种不规则的HTML写法,比如img属性换行、单双引号包裹属性等场景

内容的提问来源于stack exchange,提问作者user3164444

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 16:03:01