」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 Python 建立元搜尋引擎:逐步指南

使用 Python 建立元搜尋引擎:逐步指南

發佈於2024-08-28
瀏覽:190

Building a Meta Search Engine in Python: A Step-by-Step Guide在当今的数字时代,信息丰富,但找到正确的数据可能是一个挑战。元搜索引擎聚合来自多个搜索引擎的结果,提供更全面的可用信息视图。在这篇博文中,我们将逐步介绍用 Python 构建一个简单的元搜索引擎的过程,包括错误处理、速率限制和隐私功能。

什么是元搜索引擎?

元搜索引擎不维护自己的索引页面数据库。相反,它将用户查询发送到多个搜索引擎,收集结果,并以统一的格式呈现它们。这种方法允许用户访问更广泛的信息,而无需单独搜索每个引擎。

先决条件

要学习本教程,您需要:

  • 您的计算机上已安装 Python(最好是 Python 3.6 或更高版本)。
  • Python编程基础知识。
  • Bing 搜索的 API 密钥(您可以注册免费套餐)。

第 1 步:设置您的环境

首先,确保您安装了必要的库。我们将使用 requests 来发出 HTTP 请求,使用 json 来处理 JSON 数据。

您可以使用pip安装requests库:

pip install requests

第 2 步:定义您的搜索引擎

创建一个名为meta_search_engine.py 的新Python 文件,并首先定义要查询的搜索引擎。在此示例中,我们将使用 DuckDuckGo 和 Bing。

import requests
import json
import os
import time

# Define your search engines
SEARCH_ENGINES = {
    "DuckDuckGo": "https://api.duckduckgo.com/?q={}&format=json",
    "Bing": "https://api.bing.microsoft.com/v7.0/search?q={}&count=10",
}

BING_API_KEY = "YOUR_BING_API_KEY"  # Replace with your Bing API Key

第三步:实现查询功能

接下来,创建一个函数来查询搜索引擎并检索结果。我们还将实施错误处理以优雅地管理网络问题。

def search(query):
    results = []

    # Query DuckDuckGo
    ddg_url = SEARCH_ENGINES["DuckDuckGo"].format(query)
    try:
        response = requests.get(ddg_url)
        response.raise_for_status()  # Raise an error for bad responses
        data = response.json()
        for item in data.get("RelatedTopics", []):
            if 'Text' in item and 'FirstURL' in item:
                results.append({
                    'title': item['Text'],
                    'url': item['FirstURL']
                })
    except requests.exceptions.RequestException as e:
        print(f"Error querying DuckDuckGo: {e}")

    # Query Bing
    bing_url = SEARCH_ENGINES["Bing"].format(query)
    headers = {"Ocp-Apim-Subscription-Key": BING_API_KEY}
    try:
        response = requests.get(bing_url, headers=headers)
        response.raise_for_status()  # Raise an error for bad responses
        data = response.json()
        for item in data.get("webPages", {}).get("value", []):
            results.append({
                'title': item['name'],
                'url': item['url']
            })
    except requests.exceptions.RequestException as e:
        print(f"Error querying Bing: {e}")

    return results

第 4 步:实施速率限制

为了防止达到 API 速率限制,我们将使用 time.sleep() 实现一个简单的速率限制器。

# Rate limit settings
RATE_LIMIT = 1  # seconds between requests

def rate_limited_search(query):
    time.sleep(RATE_LIMIT)  # Wait before making the next request
    return search(query)

第 5 步:添加隐私功能

为了增强用户隐私,我们将避免记录用户查询并实施缓存机制来临时存储结果。

CACHE_FILE = 'cache.json'

def load_cache():
    if os.path.exists(CACHE_FILE):
        with open(CACHE_FILE, 'r') as f:
            return json.load(f)
    return {}

def save_cache(results):
    with open(CACHE_FILE, 'w') as f:
        json.dump(results, f)

def search_with_cache(query):
    cache = load_cache()
    if query in cache:
        print("Returning cached results.")
        return cache[query]

    results = rate_limited_search(query)
    save_cache({query: results})
    return results

第 6 步:删除重复项

为了确保结果是唯一的,我们将实现一个根据 URL 删除重复项的功能。

def remove_duplicates(results):
    seen = set()
    unique_results = []
    for result in results:
        if result['url'] not in seen:
            seen.add(result['url'])
            unique_results.append(result)
    return unique_results

第 7 步:显示结果

创建一个函数,以用户友好的格式显示搜索结果。

def display_results(results):
    for idx, result in enumerate(results, start=1):
        print(f"{idx}. {result['title']}\n   {result['url']}\n")

第8步:主要功能

最后,将所有内容集成到运行元搜索引擎的主函数中。

def main():
    query = input("Enter your search query: ")
    results = search_with_cache(query)
    unique_results = remove_duplicates(results)
    display_results(unique_results)

if __name__ == "__main__":
    main()

完整代码

这是元搜索引擎的完整代码:

import requests
import json
import os
import time

# Define your search engines
SEARCH_ENGINES = {
    "DuckDuckGo": "https://api.duckduckgo.com/?q={}&format=json",
    "Bing": "https://api.bing.microsoft.com/v7.0/search?q={}&count=10",
}

BING_API_KEY = "YOUR_BING_API_KEY"  # Replace with your Bing API Key

# Rate limit settings
RATE_LIMIT = 1  # seconds between requests

def search(query):
    results = []

    # Query DuckDuckGo
    ddg_url = SEARCH_ENGINES["DuckDuckGo"].format(query)
    try:
        response = requests.get(ddg_url)
        response.raise_for_status()
        data = response.json()
        for item in data.get("RelatedTopics", []):
            if 'Text' in item and 'FirstURL' in item:
                results.append({
                    'title': item['Text'],
                    'url': item['FirstURL']
                })
    except requests.exceptions.RequestException as e:
        print(f"Error querying DuckDuckGo: {e}")

    # Query Bing
    bing_url = SEARCH_ENGINES["Bing"].format(query)
    headers = {"Ocp-Apim-Subscription-Key": BING_API_KEY}
    try:
        response = requests.get(bing_url, headers=headers)
        response.raise_for_status()
        data = response.json()
        for item in data.get("webPages", {}).get("value", []):
            results.append({
                'title': item['name'],
                'url': item['url']
            })
    except requests.exceptions.RequestException as e:
        print(f"Error querying Bing: {e}")

    return results

def rate_limited_search(query):
    time.sleep(RATE_LIMIT)
    return search(query)

CACHE_FILE = 'cache.json'

def load_cache():
    if os.path.exists(CACHE_FILE):
        with open(CACHE_FILE, 'r') as f:
            return json.load(f)
    return {}

def save_cache(results):
    with open(CACHE_FILE, 'w') as f:
        json.dump(results, f)

def search_with_cache(query):
    cache = load_cache()
    if query in cache:
        print("Returning cached results.")
        return cache[query]

    results = rate_limited_search(query)
    save_cache({query: results})
    return results

def remove_duplicates(results):
    seen = set()
    unique_results = []
    for result in results:
        if result['url'] not in seen:
            seen.add(result['url'])
            unique_results.append(result)
    return unique_results

def display_results(results):
    for idx, result in enumerate(results, start=1):
        print(f"{idx}. {result['title']}\n   {result['url']}\n")

def main():
    query = input("Enter your search query: ")
    results = search_with_cache(query)
    unique_results = remove_duplicates(results)
    display_results(unique_results)

if __name__ == "__main__":
    main()

结论

恭喜!您已经用 Python 构建了一个简单但实​​用的元搜索引擎。该项目不仅演示了如何聚合多个来源的搜索结果,还强调了错误处理、速率限制和用户隐私的重要性。您可以通过添加更多搜索引擎、实施 Web 界面,甚至集成机器学习以提高结果排名来进一步增强此引擎。快乐编码!

版本聲明 本文轉載於:https://dev.to/thisisanshgupta/building-a-meta-search-engine-in-python-a-step-by-step-guide-1jb8?1如有侵犯,請洽study_golang@163 .com刪除
最新教學 更多>
  • PHP與C++函數重載處理的區別
    PHP與C++函數重載處理的區別
    作為經驗豐富的C開發人員脫離謎題,您可能會遇到功能超載的概念。這個概念雖然在C中普遍,但在PHP中構成了獨特的挑戰。讓我們深入研究PHP功能過載的複雜性,並探索其提供的可能性。 在PHP中理解php的方法在PHP中,函數超載的概念(如C等語言)不存在。函數簽名僅由其名稱定義,而與他們的參數列表無關...
    程式設計 發佈於2025-04-30
  • 為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    mySQL錯誤#1089:錯誤的前綴鍵錯誤descript [#1089-不正確的前綴鍵在嘗試在表中創建一個prefix鍵時會出現。前綴鍵旨在索引字符串列的特定前綴長度長度,可以更快地搜索這些前綴。 了解prefix keys `這將在整個Movie_ID列上創建標準主鍵。主密鑰對於唯一識...
    程式設計 發佈於2025-04-30
  • 在程序退出之前,我需要在C ++中明確刪除堆的堆分配嗎?
    在程序退出之前,我需要在C ++中明確刪除堆的堆分配嗎?
    在C中的顯式刪除 在C中的動態內存分配時,開發人員通常會想知道是否需要手動調用“ delete”操作員在heap-exprogal exit exit上。本文深入研究了這個主題。 在C主函數中,使用了動態分配變量(HEAP內存)的指針。當應用程序退出時,此內存是否會自動發布?通常,是。但是,即使在...
    程式設計 發佈於2025-04-30
  • 為什麼不````''{margin:0; }`始終刪除CSS中的最高邊距?
    為什麼不````''{margin:0; }`始終刪除CSS中的最高邊距?
    在CSS 問題:不正確的代碼: 全球範圍將所有餘量重置為零,如提供的代碼所建議的,可能會導致意外的副作用。解決特定的保證金問題是更建議的。 例如,在提供的示例中,將以下代碼添加到CSS中,將解決餘量問題: body H1 { 保證金頂:-40px; } 此方法更精確,避免了由全局保證金重置...
    程式設計 發佈於2025-04-30
  • C++20 Consteval函數中模板參數能否依賴於函數參數?
    C++20 Consteval函數中模板參數能否依賴於函數參數?
    [ consteval函數和模板參數依賴於函數參數在C 17中,模板參數不能依賴一個函數參數,因為編譯器仍然需要對非contexexpr futcoriations contim at contexpr function進行評估。 compile time。 C 20引入恆定函數,必須在編譯時進...
    程式設計 發佈於2025-04-30
  • 如何同步迭代並從PHP中的兩個等級陣列打印值?
    如何同步迭代並從PHP中的兩個等級陣列打印值?
    同步的迭代和打印值來自相同大小的兩個數組使用兩個數組相等大小的selectbox時,一個包含country代碼的數組,另一個包含鄉村代碼,另一個包含其相應名稱的數組,可能會因不當提供了exply for for for the uncore for the forsion for for ytry...
    程式設計 發佈於2025-04-30
  • 如何將來自三個MySQL表的數據組合到新表中?
    如何將來自三個MySQL表的數據組合到新表中?
    mysql:從三個表和列的新表創建新表 答案:為了實現這一目標,您可以利用一個3-way Join。 選擇p。 *,d.content作為年齡 來自人為p的人 加入d.person_id = p.id上的d的詳細信息 加入T.Id = d.detail_id的分類法 其中t.taxonomy ...
    程式設計 發佈於2025-04-30
  • 如何使用FormData()處理多個文件上傳?
    如何使用FormData()處理多個文件上傳?
    )處理多個文件輸入時,通常需要處理多個文件上傳時,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    程式設計 發佈於2025-04-30
  • Java字符串非空且非null的有效檢查方法
    Java字符串非空且非null的有效檢查方法
    檢查字符串是否不是null而不是空的if (str != null && !str.isEmpty())Option 2: str.length() == 0For Java versions prior to 1.6, str.length() == 0 can be二手: if(str!= n...
    程式設計 發佈於2025-04-30
  • 使用Bootstrap創建自定義文件上傳按鈕的技巧
    使用Bootstrap創建自定義文件上傳按鈕的技巧
    使用bootstrap 對於Bootstrap 3、4和5,可以簡單地使用HTML解決方案: 瀏覽 此隱藏的輸入元素將在維護自定義按鈕樣式的同時作為常規文件輸入控件。 如果需要與IE8和下面的兼容,請使用IE8和下面,組合: { 位置:絕對; 頂部:0; 右...
    程式設計 發佈於2025-04-30
  • 大批
    大批
    [2 數組是對象,因此它們在JS中也具有方法。 切片(開始):在新數組中提取部分數組,而無需突變原始數組。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    程式設計 發佈於2025-04-30
  • 如何有效地選擇熊貓數據框中的列?
    如何有效地選擇熊貓數據框中的列?
    在處理數據操作任務時,在Pandas DataFrames 中選擇列時,選擇特定列的必要條件是必要的。在Pandas中,選擇列的各種選項。 選項1:使用列名 如果已知列索引,請使用ILOC函數選擇它們。請注意,python索引基於零。 df1 = df.iloc [:,0:2]#使用索引0和1 ...
    程式設計 發佈於2025-04-30
  • 為什麼在我的Linux服務器上安裝Archive_Zip後,我找不到“ class \” class \'ziparchive \'錯誤?
    為什麼在我的Linux服務器上安裝Archive_Zip後,我找不到“ class \” class \'ziparchive \'錯誤?
    Class 'ZipArchive' Not Found Error While Installing Archive_Zip on Linux ServerSymptom:When attempting to run a script that utilizes the ZipAr...
    程式設計 發佈於2025-04-30
  • C++中何時選擇大括號初始化?
    C++中何時選擇大括號初始化?
    brace-initioner:在C 11中確定其最佳用法介紹提供各種選項的各種選項》中為變量提供了各種選項。 This flexibility can lead to confusion and uncertainty about the most appropriate initializa...
    程式設計 發佈於2025-04-30
  • 如何使用Python的請求和假用戶代理繞過網站塊?
    如何使用Python的請求和假用戶代理繞過網站塊?
    如何使用Python的請求模擬瀏覽器行為,以及偽造的用戶代理提供了一個用戶 - 代理標頭一個有效方法是提供有效的用戶式header,以提供有效的用戶 - 設置,該標題可以通過browser和Acterner Systems the equestersystermery和操作系統。通過模仿像Chro...
    程式設計 發佈於2025-04-30

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3