如何使用 Boto3 啟動 AWS Glue 資料目錄中爬蟲的排程程式


本文將介紹使用者如何啟動 AWS Glue 資料目錄中爬蟲的排程程式。

示例

啟動 AWS Glue 資料目錄中可用的爬蟲排程程式。

問題陳述:使用 Python 中的 boto3 庫啟動爬蟲的排程程式。

解決此問題的方法/演算法

  • 步驟 1:匯入 **boto3** 和 **botocore** 異常以處理異常。

  • 步驟 2:**crawler_name** 是此函式中必需的引數。

  • 步驟 3:使用 **boto3 庫**建立 AWS 會話。確保在預設配置檔案中提到了 **region_name**。如果未提及,則在建立會話時顯式傳遞 **region_name**。

  • 步驟 4:為 **glue** 建立 AWS 客戶端。

  • 步驟 5:現在使用 **start_crawler_schedule 函式**並將引數 **crawler_name** 作為 CrawlerName 傳遞。

  • 步驟 6:它返回響應元資料並將爬蟲的排程狀態設定為 SCHEDULED。如果爬蟲的狀態正在執行或排程狀態已經是 SCHEDULED,則它會丟擲異常 - **SchedulerRunningException**。

  • 步驟 7:如果啟動爬蟲的排程程式時出現問題,請處理通用異常。

示例程式碼

以下程式碼啟動爬蟲的排程程式:

import boto3
from botocore.exceptions import ClientError

def start_scheduler_of_a_crawler(crawler_name)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.start_crawler_schedule(CrawlerName=crawler_name)
      return response
   except ClientError as e:
      raise Exception("boto3 client error in start_scheduler_of_a_crawler: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in start_scheduler_of_a_crawler: " + e.__str__())
print(start_scheduler_of_a_crawler("Data Dimension"))

輸出

{'ResponseMetadata': {'RequestId': '73e50130-*****************8e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 07:26:55 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '73e50130-***************8e'}, 'RetryAttempts': 0}}

更新於:2021年4月15日

瀏覽量 180

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.