728x90
반응형
012
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1> HTML File </h1>
html file을 이용한 웹페이지 </br>
<p> <a href = "http://www.cbs.com">CBS</a>로 이동</p>
</body>
</html>
크롤링 하다보면 직접할 수 없는 경우가 있다.
그런 사이트들을 대비해서 하는 것
방법 :파일 전체를 다운로드 한다음 파일을 불러서 크롤링 실행하면 된다.
//
// ViewController.swift
// Kanna_02
//
// Created by Mac on 2020/09/01.
// Copyright © 2020 MyMac. All rights reserved.
//
import UIKit
import Kanna
// 가끔 직접 크롤링을 할 수 없을 떄가 있다. 그래서 그걸 대비하기 위해서 htmlView.html을 만들고 수업하는중
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
dataCrawling()
}
func dataCrawling(){
// 파일 읽는 것 부터 한다. // 파일명 // 확장자
let filePath = Bundle.main.path(forResource: "htmlView", ofType: "html") // IOS 에서는 파일 읽을 때 Bundle로 시작한다.
let myUrl = URL(fileURLWithPath: filePath!)
do{
let htmlData = try String(contentsOf: myUrl, encoding: .utf8)
let doc = try HTML(html: htmlData, encoding: .utf8)
print(doc.text!)
print("----------------------------")
// h1
for h1 in doc.xpath("//h1"){
print(h1.text!)
}
print("----------------------------")
// p
for p in doc.xpath("//p"){
print(p.text!)
}
print("----------------------------")
// a
}catch let error{
print("Error \(error)")
}
}
}
반응형