3

I am trying to make Swift scrape websites using SwiftSoup. However, websites like: https://apple.news/AQZXxg8mUQfKrEaM9MRBpxw , it redirects automatically using JavaScript which causes SwiftSoup to scrape the opening page instead of the actual article that I want. How should I scrape this link so that it would scrape the actual article in question rather than the cover webpage that redirects?

I have tried to use status code but this particular website does not give a status code of 301 or 302, and gives a status code of 200. I tried scraping the JavaScript portion of the HTML of the link but I don't exactly know what to do with it.

WannaInternet
  • 327
  • 1
  • 6
  • 14

1 Answers1

0
func redirectUrl() {

    let url = URL(string: "https://apple.news/AQZXxg8mUQfKrEaM9MRBpxw")!

    URLSession.shared.dataTask(with: url) { (data, response, error) in

        let html = String(data: data!, encoding: .utf8) ?? "none"
        self.parse(html: html)

    }.resume()


}

func parse(html: String) {

    do {

        let doc = try SwiftSoup.parse(html)
        let link: Element = try doc.select("a").first()!
        let linkHref = try link.attr("href")

        print(linkHref)
    } catch let error {
        print(error.localizedDescription)
    }

}

This will be in the print

https://www.npr.org/2019/06/18/733401736/npr-identifies-fourth-attacker-in-civil-rights-era-cold-case

This will work for redirect url

func redirectLink(url: URL, completion: @escaping (URL?) -> Void) {

    var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15.0)
    request.httpMethod = "HEAD"

    URLSession.shared.dataTask(with: request) { (data, response, error) in

        if let response = response {
            completion(response.url)
        }

    }.resume()

}
Salman500
  • 1,213
  • 1
  • 17
  • 35