捕獲和轉換Web的工具

適用於ASP.NET的Web Scraper API

ASP.NET Scraper API

首先 下載 使用適用於ASP.NET的Web Scraper API,並檢查示例Web項目中的handler.ashx以開始使用。

處理刮取的數據

處理已抓取數據的最簡單方法是將數據作為JSON或XML對象進行訪問,因為這使數據易於操作和查詢。 JSON將以以下通用格式進行構造,以數據集名稱作為對象屬性,本身包含一個對像數組,每個列名稱作為另一個屬性。

{
  "Items": [
    {
      "Column_One": "https://grabz.it/",
      "Column_Two": "Found"
    },
    {
      "Column_One": "http://dfadsdsa.com/",
      "Column_Two": "Missing"
    }]
}

首先必須記住,將向處理程序發送所有已抓取的數據,其中可能包括無法轉換為JSON或XML對象的數據。 因此,在處理之前,必須檢查您接收到的數據類型。

但是,使用ASP.NET API時需要額外的步驟才能讀取JSON或XML文件,在其中創建與所需數據結構匹配的類。 下面顯示了一個示例,其中創建了兩個類定義來保存上述JSON數據結構。

public class DataSet
{
    public List<Item> Items;
}

public class Item
{
    public string Column_One;
    public string Column_Two;
}

這些類現在用於轉換JSON文件 int可用的對象結構。 在下面的示例中,下面的ScrapeResult構造函數正在接收HttpRequest類,但是它也接受HttpRequestBase類以使其與ASP.NET MVC Web項目兼容。

ScrapeResult scrapeResult = new ScrapeResult(context.Request);

if (scrapeResult.Extension == "json")
{
    DataSet dataSet = scrapeResult.FromJSON<DataSet>();
    foreach (Item item in dataSet.Items)
    {
        if (item.Column_Two == "Found")
        {
            //do something
        }
        else
        {
            //do something else
        }
    }
}
else
{
    //probably a binary file etc save it
    scrapeResult.save(context.Server.MapPath("~/results/" + scrapeResult.Filename));
}

上面的示例顯示瞭如何遍歷數據集類的所有結果以及如何根據 Column_Two 屬性。 另外,如果處理程序收到的文件不是JSON文件,那麼它僅僅是 saved到結果目錄。 儘管ScrapeResult類確實嘗試確保所有發布的文件都來自GrabzIt的服務器,但在文件擴展名之前也應進行檢查。 saved.

ScrapeResult方法和屬性

下面列出了可用於處理抓取結果的ScrapeResult類的所有方法和屬性。

調試

調試ASP.NET處理程序的最好方法是從 網頁抓取 頁, save 遇到問題的文件到可訪問的位置,然後將該文件的路徑傳遞給ScrapeResult類的構造函數。 這使您可以調試處理程序,而不必每次都進行新的抓取,如下所示。

ScrapeResult scrapeResult = new ScrapeResult("data.json");

#the rest of your handler code remains the same

控制刮擦

使用GrabzIt的Web Scraper API,您還可以根據需要更改刮擦的狀態,啟動,停止或禁用刮擦。 在下面的示例中,通過傳遞刮擦ID以及所需的刮擦狀態來顯示這一點 ScrapeStatus 枚舉 SetScrapeStatus 方法。

GrabzItScrapeClient client = new GrabzItScrapeClient("Sign in to view your Application Key", "Sign in to view your Application Secret");
//Get all of our scrapes
GrabzItScrape[] myScrapes = client.GetScrapes();
if (myScrapes.Length == 0)
{
    throw new Exception("You haven't created any scrapes yet! Create one here: https://grabz.it/scraper/scrape/");
}
//Start the first scrape
client.SetScrapeStatus(myScrapes[0].ID, ScrapeStatus.Start);
if (myScrapes[0].Results.Length > 0)
{
    //re-send first scrape result if it exists
    client.SendResult(myScrapes[0].ID, myScrapes[0].Results[0].ID);
}

GrabzItScrapeClient方法和屬性

下面列出了可用於控制刮擦的GrabzItScrapeClient類的所有方法和屬性。

  • SetLocalProxy(string proxyUrl) -將本地代理服務器設置為用於所有請求。