首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在python中从google搜索中排除某些网站?

在Python中,可以使用Google搜索的自定义搜索引擎(Custom Search Engine)API来排除某些网站。以下是一个实现这个功能的示例代码:

代码语言:txt
复制
import requests

def google_search(query, exclude_sites):
    api_key = "YOUR_API_KEY"  # 替换为你的Google自定义搜索引擎API密钥
    cx = "YOUR_CX"  # 替换为你的Google自定义搜索引擎ID

    url = f"https://www.googleapis.com/customsearch/v1?key={api_key}&cx={cx}&q={query}&num=10"
    response = requests.get(url)
    results = response.json()

    filtered_results = []
    for item in results.get("items", []):
        link = item.get("link", "")
        if not any(site in link for site in exclude_sites):
            filtered_results.append(item)

    return filtered_results

# 示例用法
query = "云计算"
exclude_sites = ["example.com", "example2.com"]  # 替换为你想要排除的网站域名
results = google_search(query, exclude_sites)

for result in results:
    title = result.get("title", "")
    link = result.get("link", "")
    print(f"{title}: {link}")

在上述代码中,你需要替换YOUR_API_KEYYOUR_CX为你的Google自定义搜索引擎API密钥和ID。query变量表示你要搜索的关键词,exclude_sites变量是一个列表,包含你想要排除的网站域名。

这段代码使用了requests库发送HTTP请求,并解析返回的JSON结果。它遍历搜索结果中的每个条目,检查链接是否包含任何要排除的网站域名。如果链接不包含任何要排除的网站域名,就将该条目添加到filtered_results列表中。

最后,代码打印了过滤后的搜索结果的标题和链接。

请注意,这个示例代码仅演示了如何使用Google自定义搜索引擎API排除某些网站。在实际使用中,你需要自行申请Google自定义搜索引擎API密钥和ID,并根据自己的需求进行调整。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券