用 Objective-C 或 Ruby 创建动态网页爬虫。
创建爬虫
#import "IGScraperKit.h"
IGScraper* scraper = [IGScraper scraperWithBlock:^id(IGXMLNode* node, NSString* url) {
return [[[node queryWithXPath:@"//p"] firstObject] text];
}];
然后使用爬虫抓取 HTML
[scraper scrape:@"<html><p>Hello World</p></html>" URL:nil];
// => @"Hello World"
#import "IGScraperKit.h"
IGScraperRecipe* recipe = [[IGScraperRecipe alloc] init];
[recipe addURLPattern:[NSRegularExpression regularExpressionWithPattern:@"https://www\.google\.com/search\?q=.+" options:0 error:nil]
withScraperBlock:^id(IGXMLNode *node, NSString *url) {
// handling for the page ...
return data;
}];
[recipe addURLPattern:[NSRegularExpression regularExpressionWithPattern:@"https://www\.google\.com/" options:0 error:nil]
withScraperBlock:^id(IGXMLNode *node, NSString *url) {
// handling for the page ...
return data;
}];
[recipe scrapeWithHTML:html URL:URL];
如果您想要更动态的东西,您可以用 Ruby 定义一个 Recipe
# A recipe scrape page based on URL
class GoogleRecipe < ScraperKit::Recipe
title "Google Search"
# define a HTML scraper by `on url`, where url can be a string or a Regexp
on %r{https://www\.google\.com/search\?q=.+} do
# doc is a HTMLDoc object represent the document
doc.xpath('//h3/a').collect {|node| node.text }
end
# if the page you need to parse is not HTML
# use `on_text url`
on_text %r{https://www\.google\.com/search\.json.+} do
# doc is a string of the document
JSON.parse(doc)
end
end
然后将 recipe 载入 IGRecipeRegistry 并解析页面
#import "IGScraperKit.h"
// load the recipe
NSString* path = [[NSBundle mainBundle] pathForResource:@"google" ofType:@"rb"];
NSString* recipe = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
IGRecipeRegistry* registry = [[IGRecipeRegistry alloc] init];
[registry loadRecipe:Recipe(@"walmart")];
NSArray* result = [registry scrapeWithHTML:html url:@"https://www.google.com/search?q=doughnuts"];
// => <__NSArrayM 0xed85590>(
// Doughnut - Wikipedia, the free encyclopedia,
// Home - Krispy Kreme Doughnuts and Coffee,
// Voodoo Doughnut - The Magic is in the Hole!!!,
//【超人氣甜甜圈】Krispy Kreme Doughnuts 、台北店 ... - Yam天空部落,
// Doughnut Recipes - Allrecipes.com,
// Doughnut Plant,
// Revolution Doughnuts,
// Sidecar Doughnuts & Coffee,
// Top Pot Hand-Forged Doughnuts,
// Lucky's Doughnuts
// )
要使用此功能,您需要包含 JavaScriptCore 框架(iOS 7、OS X 10.9)并在导入 IGScraperKit.h
之前定义 IGSCRAPERKIT_ENABLE_SCRIPTING。
要通过 CocoaPods 安装 IGScraperKit,请将以下行添加到您的 Podfile 中
pod "IGScraperKit", '0.3.1'
使用 Ruby 支持
pod "IGScraperKit/Scripting", '0.3.1'
bundle install
pod install
MIT 许可证。查看 LICENSE.txt。