• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

nolanw/HTMLReader: A WHATWG-compliant HTML parser in Objective-C.

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

nolanw/HTMLReader

开源软件地址:

https://github.com/nolanw/HTMLReader

开源编程语言:

Objective-C 98.2%

开源软件介绍:

HTMLReader

A WHATWG-compliant HTML parser with CSS selectors in Objective-C and Foundation. It parses HTML just like a browser.

Supports iOS, OS X, tvOS, and watchOS

Usage

A quick example of parsing an inline document and finding the bold text:

import HTMLReader

let document = HTMLDocument(string: """
    <p>
        Ahoy there, <b>sailor</b>!
    </p>
    """)
print(document.firstNode(matchingSelector: "b")?.textContent ?? "")
// => sailor

Manipulating a document is a little more involved, but entirely doable. Here we take the document from the first example and wrap the paragraph within a new element:

if
    let p = document.firstNode(matchingSelector: "p"),
    let parent = p.parent
{
    let wrapper = HTMLElement(tagName: "div", attributes: ["class": "special"])
    let children = parent.mutableChildren
    children.insert(wrapper, at: children.index(of: p))
    p.parent = wrapper
}

print(document.innerHTML)
// => <html><head></head><body><div class="special"><p>\
//        Ahoy there, <b>sailor</b>!\
//    </p></div></body></html>

You can save a document as a file:

let serialized = document.serializedFragment
let temp = FileManager.default.temporaryDirectory
let fileURL = temp.appendPathComponent("nifty.html", isDirectory: false)
do {
    try serialized.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
    print("Could not save nifty document", error)
}

Finally, the most involved example: fetching the main page for the HTMLReader repository and scraping the description of the project. (This is just an example; GitHub has a fabulous API that you should use if you want to find a repository's description!)

@import HTMLReader;

// Load a web page.
NSURL *url = [NSURL URLWithString:@"https://github.com/nolanw/HTMLReader"];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url completionHandler:
  ^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *contentType = nil;
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields];
        contentType = headers[@"Content-Type"];
    }
    HTMLDocument *home = [HTMLDocument documentWithData:data
                                      contentTypeHeader:contentType];
    HTMLElement *div = [home firstNodeMatchingSelector:@".repository-meta-content"];
    NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSLog(@"%@", [div.textContent stringByTrimmingCharactersInSet:whitespace]);
    // => A WHATWG-compliant HTML parser in Objective-C.
}] resume];

Installation

You have choices:

  • Copy the files in the Sources folder into your project.

  • Add the following line to your Cartfile:

    github "nolanw/HTMLReader"

  • Add the following line to your Podfile:

    pod "HTMLReader"

  • Add the following line to your Package.swift:

    .package(url: "https://github.com/nolanw/HTMLReader", from: "2.1.6")

  • Add the package in Xcode by selecting File > Swift Packages > Add Package Dependency and enter the URL https://github.com/nolanw/HTMLReader.

  • Clone this repository (perhaps add it as a submodule) and add HTMLReader.xcodeproj to your project/workspace. Then add HTMLReader.framework to your app target. (Or, if you're targeting iOS earlier than 8.0: add libHTMLReader.a to your app target and "$(SYMROOT)/include" to your app target's Header Search Paths.)

HTMLReader has no dependencies other than Foundation.

Why HTMLReader?

I needed to scrape HTML like a browser. I couldn't find a good choice for iOS.

The Alternatives

libxml2 ships with iOS. It parses some variant of HTML 4 (?) and does not handle new/broken markup like a modern browser.

Other Objective-C and Swift libraries I come across (e.g. Fuzi, hpple, Kanna, Ono) use libxml2 and inherit its shortcomings.

SwiftSoup is a Swift port of Jsoup. It didn't exist when I made HTMLReader. (To be fair, publicly, neither did Swift.)

There are C libraries such as Gumbo or Hubbub, but you need to shuffle data to and from Objective-C or Swift. (Also Gumbo wasn't publicly announced until after HTMLReader was far along.)

WebKit ships with iOS, but its HTML parsing abilities are considered private API. I consider a round-trip through a web view inappropriate for parsing HTML. And I didn't make it very far into building my own copy of WebCore.

Google Toolbox for Mac will escape and unescape strings for HTML (e.g. &amp;&) but, again, not like a modern browser. For example, GTM will not unescape &#65 (note the missing semicolon).

CFStringTransform does numeric entities via (the reversible) kCFStringTransformToXMLHex, but that rules out named entities.

Does it work?

HTMLReader continually runs html5lib's tokenization and tree construction tests, ignoring the tests for <template> (which HTMLReader does not implement). Note that you need to check out the HTMLReaderTests/html5lib Git submodule in order to actually run these tests.

HTMLReader is continually built and tested on iOS versions 8.4, 9.3, 10.3, and 11.0; built and tested on macOS versions 10.9, 10.10, 10.11, 10.12, and 10.13; built and tested on tvOS versions 9.2, 10.2, and 11.0; and built on watchOS versions 2.2, 3.2, and 4.0. It should work on down to iOS 5, macOS 10.7, tvOS 9.0, and watchOS 2.0, but there is no automated testing there (it's ok to file an issue though!).

Given all that: Build Status

HTMLReader is used by at least one shipping app.

How fast is it?

I'm not sure.

Included in the project is a utility called Benchmarker. It knows how to run three tests:

  • Parsing a large HTML file. In this case, the 7MB single-page HTML specification.
  • Escaping and unescaping entities in the large HTML file.
  • Running a bunch of CSS selectors. Basically copied from a WebKit performance test.

Changes to HTMLReader should not cause these benchmarks to run slower. Ideally changes make them run faster!

Bugs and Feature Requests

Bugs can be reported, and features can be requested, using the issue tracker. Or get in touch directly if you'd prefer.

License

HTMLReader is in the public domain.

Acknowledgements

HTMLReader is developed by Nolan Waite.

Thanks to Chris Williams for contributing the implementation of CSS selectors.




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap