Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift get content of html from url

Tags:

html

ios10

swift3

let myURLString = "https://en.wiktionary.org/wiki/see"

    if let myURL = NSURL(string: myURLString) { 


      let myHTMLString = String(contentsOfURL: myURL, encoding: String.Encoding.utf8)
      print("HTML : \(myHTMLString)")

    }

And I got printed:

HTML : (https://en.wiktionary.org/wiki/see, Unicode (UTF-8))

But instead I need html content. What I am doing wrong?

Update:
As a source for the code I used: How To Get HTML source from URL with Swift

Please, read my question with more attention, as the result I got text of link, but instead I need text of html page

like image 800
spin_eight Avatar asked Jan 21 '26 19:01

spin_eight


2 Answers

Try this:

let myURLString = "http://google.com"
guard let myURL = NSURL(string: myURLString) else {
    print("Error: \(myURLString) doesn't seem to be a valid URL")
    return
}

do {
    let myHTMLString = try String(contentsOfURL: myURL)
    print("HTML : \(myHTMLString)")
} catch let error as NSError {
    print("Error: \(error)")
}

Hope this helps!

like image 106
Mr. Xcoder Avatar answered Jan 23 '26 12:01

Mr. Xcoder


To retrieve the HTML of the webpage referenced by a url you just need to

let myURLString = "https://en.wiktionary.org/wiki/see"

if let
    url = NSURL(string: myURLString),
    html = try? String(contentsOfURL: url)  {
    print(html)
}

I tested this code in my Playground and it is retrieving the full HTML of the web page.

like image 40
Luca Angeletti Avatar answered Jan 23 '26 12:01

Luca Angeletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!