Skip to main content
 首页 » 编程设计

python之使用新的自定义搜索 API 在 Google 图像上搜索图像

2025年05月04日30luoye11

所以,我正在测试这段代码:

import requests 
import json 
 
 
searchTerm = 'parrot' 
startIndex = '0' 
searchUrl = "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + \ 
    searchTerm + "&start=" + startIndex 
r = requests.get(searchUrl) 
response = r.content.decode('utf-8') 
result = json.loads(response) 
print(r) 
print(result) 

响应是:

<Response [200]> 
{'responseData': None, 'responseStatus': 403, 'responseDetails': 'This API is no longer available.'} 

似乎我正在尝试使用旧的 API,现在它已被弃用。当我检查 Google Custom Search API我看不出有什么方法可以直接在谷歌图片上搜索,这是否可以通过新的 API 实现?

请您参考如下方法:

有可能,这里是新的 API 引用:
https://developers.google.com/custom-search/json-api/v1/reference/cse/list

import requests 
import json 
 
searchTerm = 'parrot' 
startIndex = '1' 
key = ' Your API key here. ' 
cx = ' Your CSE ID:USER here. ' 
searchUrl = "https://www.googleapis.com/customsearch/v1?q=" + \ 
    searchTerm + "&start=" + startIndex + "&key=" + key + "&cx=" + cx + \ 
    "&searchType=image" 
r = requests.get(searchUrl) 
response = r.content.decode('utf-8') 
result = json.loads(response) 
print(searchUrl) 
print(r) 
print(result) 

很好用,我刚刚试过了。