如何按条件返回Google图片搜索结果并实现天气穿搭生成Web应用
根据天气条件返回Google图片搜索结果的实现方案
你已经搭好了天气穿搭应用的基础框架,要实现根据天气条件返回对应Google图片搜索结果,得注意Google的搜索规则——直接爬取图片结果是违反服务条款的,所以推荐用官方的Google Custom Search JSON API来合法获取图片。下面是具体的实现步骤:
第一步:准备Google API资源
先完成几个前置操作:
- 登录Google Cloud控制台创建新项目
- 在项目中启用「Custom Search API」
- 生成一个API密钥(用于API调用的身份验证)
- 创建自定义搜索引擎,设置为允许搜索整个网络(这样才能搜到全网的穿搭图片)
第二步:修改getForecastOutfit函数
因为API调用是异步操作,我们把函数改成异步函数,根据温度生成穿搭关键词,再调用API获取图片链接:
async function getForecastOutfit(forecast) { // 根据温度区间定义对应的穿搭关键词 let outfitKeyword; if (forecast.temp.f > 80) { outfitKeyword = "summer casual daily outfit"; } else if (forecast.temp.f > 60) { outfitKeyword = "spring fall casual outfit"; } else if (forecast.temp.f > 32) { outfitKeyword = "light winter warm outfit"; } else { outfitKeyword = "heavy winter insulated outfit"; } // 替换成你自己的API密钥和自定义搜索引擎ID const apiKey = "YOUR_GOOGLE_API_KEY"; const searchEngineId = "YOUR_CUSTOM_SEARCH_ENGINE_ID"; // 构建API请求URL,指定搜索类型为图片 const searchUrl = `https://www.googleapis.com/customsearch/v1?q=${encodeURIComponent(outfitKeyword)}&cx=${searchEngineId}&searchType=image&key=${apiKey}`; try { // 发送请求并解析响应 const response = await fetch(searchUrl); const searchResult = await response.json(); // 返回搜索到的第一张图片链接,没有结果则用备用图 if (searchResult.items && searchResult.items.length > 0) { return searchResult.items[0].link; } else { return "http://your/fallback/image/url"; } } catch (error) { console.error("获取穿搭图片失败:", error); return "http://your/fallback/image/url"; } }
第三步:正确调用异步函数
现在函数是异步的,调用时需要用await(在异步函数内)或者.then()来处理返回的图片链接:
// 假设你已经获取到了forecast数据 getForecastOutfit(yourForecastData) .then(imageUrl => { // 将图片展示到页面上,比如设置img元素的src属性 const outfitImg = document.getElementById("outfit-image"); if (outfitImg) outfitImg.src = imageUrl; }) .catch(err => console.error("处理图片链接出错:", err));
备选方案:使用免费图片API
如果觉得Google API的设置繁琐或有调用限制,也可以用Unsplash的免费图片API——它提供大量高质量免费图片,使用门槛更低:
async function getForecastOutfit(forecast) { let outfitKeyword; // 同样的温度-关键词映射逻辑... // 替换成你的Unsplash Access Key const unsplashKey = "YOUR_UNSPLASH_ACCESS_KEY"; const searchUrl = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(outfitKeyword)}&client_id=${unsplashKey}`; try { const response = await fetch(searchUrl); const searchResult = await response.json(); if (searchResult.results && searchResult.results.length > 0) { // 返回中等分辨率的图片链接 return searchResult.results[0].urls.regular; } else { return "http://your/fallback/image/url"; } } catch (error) { console.error("获取图片失败:", error); return "http://your/fallback/image/url"; } }
内容的提问来源于stack exchange,提问作者anchpags
相关产品推荐
相关产品推荐

