首先 下載 Web Scraper API for Python,並查看其中的示例處理程序以開始使用。
處理已抓取數據的最簡單方法是將數據作為JSON或XML對象進行訪問,因為這使數據易於操作和查詢。 JSON將以以下通用格式進行構造,以數據集名稱作為對象屬性,本身包含一個對像數組,每個列名稱作為另一個屬性。
{ "Dataset_Name": [ { "Column_One": "https://grabz.it/", "Column_Two": "Found" }, { " Column_One": "http://dfadsdsa.com/" , "Column_Two" : "Missing" }] }
首先必須記住,將向處理程序發送所有已抓取的數據,其中可能包括無法轉換為JSON或XML對象的數據。 因此,在處理之前,必須檢查您接收到的數據類型。
scrapeResult = ScrapeResult.ScrapeResult() if scrapeResult.getExtension() == 'json': json = scrapeResult.toJSON() for json["Dataset_Name"] in obj: if obj["Column_Two"] == "Found": #do something else: #do something else else: #probably a binary file etc save it scrapeResult.save("results/"+scrapeResult.getFilename())
上面的示例顯示瞭如何遍歷數據集的所有結果 Dataset_Name
並根據 Column_Two
屬性。 另外,如果處理程序收到的文件不是JSON文件,那麼它僅僅是 saved到結果目錄。 儘管ScrapeResult類確實嘗試確保所有發布的文件都來自GrabzIt的服務器,但在文件擴展名之前也應進行檢查。 saved.
下面列出的是ScrapeResult類的所有方法,可用於處理抓取結果。
調試Python處理程序的最佳方法是從 網頁抓取 頁, save 遇到問題的文件到可訪問的位置,然後將該文件的路徑傳遞給ScrapeResult類的構造函數。 這使您可以調試處理程序,而不必每次都進行新的抓取,如下所示。
scrapeResult = ScrapeResult.ScrapeResult("data.json"); #the rest of your handler code remains the same
使用適用於Python的GrabzIt的Web Scraper API,您可以根據需要遠程啟動,停止,啟用或禁用抓取。 如以下示例所示,這是刮擦的ID以及新的刮擦狀態被傳遞到 SetScrapeStatus
方法。
client = GrabzItScrapeClient.GrabzItScrapeClient("Sign in to view your Application Key", "Sign in to view your Application Secret") //Get all of our scrapes myScrapes = client.GetScrapes() if (len(myScrapes) == 0) { raise Exception('You have not created any scrapes yet! Create one here: https://grabz.it/scraper/scrape/') } //Start the first scrape client.SetScrapeStatus(myScrapes[0].ID, "Start") if (len(myScrapes[0].Results) > 0) { //re-send first scrape result if it exists client.SendResult(myScrapes[0].ID, myScrapes[0].Results[0].ID); }
下面列出的是GrabzItScrapeClient類的所有方法和屬性,可用於控制狀態抓取。