ios

[iOS, Swift] SwiftSoup을 이용한 Crolling(웹 크롤링)

2023. 5. 24. 02:29
목차
  1. 1. SwiftSoup 라이브러리 설치
  2. 2. SwiftSoup을 사용하는데 가장 중요한 개념
  3. 3. SwiftSoup을 통한 크롤링 구현

1. SwiftSoup 라이브러리 설치

https://github.com/scinfu/SwiftSoup

 

GitHub - scinfu/SwiftSoup: SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS,

SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS) - GitHub - scinfu/SwiftSoup: SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS,...

github.com

pod 'SwiftSoup'

 

2. SwiftSoup을 사용하는데 가장 중요한 개념

1. 기본적으로 Css Selector를 통해 크롤링하고자 하는 요소에 접근합니다

크롤링하고자 하는 page -> 마우스 우클릭 -> 검사 -> 원하는 선택자에 접근 -> 마우스 우클릭 -> Copy selector

 

2. SwiftSoup의 Element속성 중 id, class, tag 는 모두 element.select()로 접근하는 반면, attribute는 element.attr()로 접근하는 것을 주의해야 합니다. (attribute는 tag 안의 값)

 

3. SwiftSoup을 통한 크롤링 구현

저의 경우 여러 의류 브랜드 사이트의 상품들을 크롤링 해야하는 상황이였으며 싱글톤을 사용하였습니다.

func crawlBrandProducts(urlStr: [String], selector: String, nameSelector: String, priceSelector: String, imageSelector: String, attrString: String, removeString: String, addHttps: Bool, productURL: String, completion: @escaping ([Brand.BrandProduct]) -> Void) {
        
        var products: [Brand.BrandProduct] = []
        
        let group = DispatchGroup()
        
        urlStr.forEach { url in
            group.enter()
            AF.request(url).responseString { (response) in
                print("url", url)
                defer { //함수의 가장 마지막에 실행
                    group.leave()
                }
                
                guard let html = response.value else {
                    return
                }
                
                do {
                    let doc: Document = try SwiftSoup.parse(html)
                    let productElements: Elements = try doc.select(selector)
                    
                    for productElement in productElements {
                        
                        let productName = try productElement.select(nameSelector).text()
                        
                        
                        let productPriceString = try? productElement.select(priceSelector).text().replacingOccurrences(of: removeString, with: "")
                        
                        var imageURL = try "https:" + productElement.select(imageSelector).attr(attrString)
                        
                        if addHttps == false {
                            imageURL = try productElement.select(imageSelector).attr(attrString)
                        }
                        
                        let productURL = try productElement.select(productURL).attr("href")
                        
                        let product = Brand.BrandProduct(productName: productName, productImageURL: imageURL, productPrice: productPriceString, productURL: productURL, productImageURLs: nil, productSpecification: nil)
                        products.append(product)
                    }
                    
                } catch {
                    print("crawl error")
                }
            }
        }
        group.notify(queue: .main) {
            completion(products)
        }
    }
  1. Alamofire를 통해 해당 사이트에 있는 html을 획득
  2. html을 파싱하여 데이터 획득

이미지의 경우 element는 다음과 같습니다 <img src="//xxxx.com/나머지 주소~">

이때, "//xxxx.com/나머지 주소~"를 크롤링 해야한다면 그 값은 tag안에 존재하므로 attribute입니다.

따라서 .attr("src")를 통해 값을 추출할 수 있습니다.

'ios' 카테고리의 다른 글

[iOS, Swift]ViewController간 데이터 전달(delegate VS property)  (0) 2023.05.23
  1. 1. SwiftSoup 라이브러리 설치
  2. 2. SwiftSoup을 사용하는데 가장 중요한 개념
  3. 3. SwiftSoup을 통한 크롤링 구현
'ios' 카테고리의 다른 글
  • [iOS, Swift]ViewController간 데이터 전달(delegate VS property)
chobo5
chobo5
개발 기록
전체
오늘
어제
chobo5
chobo5's blog
chobo5
  • 분류 전체보기
    • ios
      • 문법
      • UIKit
      • UI구현
      • 기타
    • IT
    • Java
      • 기초
      • Spring
      • JPA
    • Algorithm
    • OOP
    • SQL

블로그 메뉴

  • 홈
  • 태그
  • 방명록

인기 글

태그

  • Lazy
  • Swift
  • setter
  • static
  • property
  • restapi
  • 프로퍼티
  • didset
  • getter
  • API

최근 글

hELLO · Designed By 정상우.
chobo5
[iOS, Swift] SwiftSoup을 이용한 Crolling(웹 크롤링)
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.