2017-09-15 139 views
0

我目前正在尝试使用Kanna和Swift解析来自website的图像链接。如何从网站获取图像源 - Swift和Kanna

但是,当我尝试使用doc.css或doc.xcpath时,它不起作用。我已经使用doc.css解析标题和日期,但是,我不确定如何解析图像源。如果可能的话,如果你可以在你的答案中包含一个在我的UIImageView中使用图像链接的方法(通过IBOutlet链接),我希望它。

下面是我尝试过的代码,也是网站本身的检查元素功能的一个片段。

func parseHTML(html: String) -> Void { 
     if let doc = Kanna.HTML(html: html, encoding: String.Encoding.utf8) { 

      for link in doc.xpath(".//div[@class='loop-thumb'/a[1]/img[1]]") { 

       print(link.text)//where I am trying to get the image source 
       self.imageURLs.append(link.text)//array of all image links 
      } 

     } 
     self.postTableView.reloadData()//my tableview name 
    } 

inspect element of website

回答

0

这是我的溶液寻找的图像的源和用它来把它放在我的视图控制器。

func parseHTML(html: String) -> Void { 
     if let doc = Kanna.HTML(html: html, encoding: String.Encoding.utf8) { 

      for item in doc.xpath("//div[@class='loop-thumb']/a") {//goes through the xpath and looks at the directories for each one that matches 

       let imageURL = (item.at_xpath("img")?["src"])//gets the image source 

       if(imageURL! == "https://s0.wp.com/wp-content/themes/premium/mh-magazine/images/noimage_174x131.png"){ //checks if no image, and replaces with The Oracle placeholder image 
        self.imageURLs.append("https://scontent.fsnc1-1.fna.fbcdn.net/v/t1.0-9/12002228_10153530981476668_4060049645901806384_n.jpg?oh=daf19a8eaf94db01fddd0516e25146f8&oe=5A4F5E34")//appends placeholder image for each article with no image 
       } 
       else { 
        self.imageURLs.append(imageURL!)//appends the image URL to the array of image urls 
       } 
      } 


     }