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

如何获取Giphy图片元素中以.webp结尾的src属性值?

嘿,这个问题我碰到过!Giphy为了优化加载性能,通常会用<picture>标签来提供不同格式的图片资源,浏览器支持WebP的话就会加载WebP版本,而默认的<img>标签的src往往是作为降级方案的GIF链接,所以你直接用$('img').attr('src')拿到的是GIF很正常。下面给你几个可行的解决方案:

方法1:从<picture>标签的<source>元素中获取WebP链接

Giphy的图片结构通常是这样的:

<picture>
  <source type="image/webp" srcset="https://media.giphy.com/media/4uZv6yO0loMKc/giphy.webp">
  <img src="https://media.giphy.com/media/4uZv6yO0loMKc/giphy.gif" alt="...">
</picture>

你可以直接定位到type="image/webp"的<source>元素,获取它的src或者srcset属性:

// 获取WebP格式的图片链接
const webpSrc = $('picture source[type="image/webp"]').attr('src') || $('picture source[type="image/webp"]').attr('srcset');
console.log(webpSrc);

方法2:解析<img>元素的srcset属性

如果页面里没有用<picture>,而是给<img>设置了srcset来提供多格式资源,你可以解析srcset来提取WebP链接:

// 定位到目标Giphy图片
const giphyImg = $('img[src*="giphy.com"]');
// 获取srcset属性值
const srcsetContent = giphyImg.attr('srcset');

if (srcsetContent) {
  // 拆分srcset中的各个资源项
  const resourceEntries = srcsetContent.split(',').map(entry => entry.trim());
  // 找到以.webp结尾的项
  const webpEntry = resourceEntries.find(entry => entry.endsWith('.webp'));
  
  if (webpEntry) {
    // 提取链接(去掉后面可能的分辨率标识)
    const webpSrc = webpEntry.split(' ')[0];
    console.log(webpSrc);
  } else {
    console.log('未找到WebP格式的链接');
  }
}

注意事项:确保资源已加载完成

如果页面是动态渲染的(比如通过JS加载Giphy图片),要等页面完全加载后再执行代码,避免获取不到元素:

$(window).on('load', function() {
  // 在这里执行上面的获取代码
  const webpSrc = $('picture source[type="image/webp"]').attr('src');
  console.log(webpSrc);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:40:49