要使用Bing自定义搜索API检测提供的URL中的关键词,可以使用以下代码示例:
import requests
def search_keyword_in_url(api_key, url, keyword):
endpoint = "https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search"
headers = {
"Ocp-Apim-Subscription-Key": api_key
}
params = {
"q": keyword,
"customconfig": "your_custom_config_id",
"url": url
}
response = requests.get(endpoint, headers=headers, params=params)
if response.status_code == 200:
search_results = response.json()
if search_results['webPages']['totalEstimatedMatches'] > 0:
print(f"The keyword '{keyword}' was found in the URL '{url}'.")
else:
print(f"The keyword '{keyword}' was not found in the URL '{url}'.")
else:
print("Error:", response.status_code, response.text)
# 使用自己的API密钥和自定义配置ID
api_key = "your_api_key"
url = "https://example.com"
keyword = "example"
search_keyword_in_url(api_key, url, keyword)
请确保将your_api_key
替换为自己的Bing自定义搜索API密钥,并将your_custom_config_id
替换为自己的自定义配置ID。
上述代码使用requests
库向Bing自定义搜索API发送GET请求,并传递关键字、URL和API密钥。然后,检查API响应中webPages
下的totalEstimatedMatches
字段,以确定关键字是否在URL中找到。如果关键字存在于URL中,它将打印相应的消息,否则将打印关键字未找到的消息。
这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。