获取一个网页的全部<image src>

我需要获取当前页面UIWebView中的全部图片url。

代码如下:

- (void)webViewDidFinishLoad:(UIWebView*)webView {
    NSString *firstImageUrl = [self.webView stringByEvaluatingJavaScriptFromString:@"var images = document.getElementsByTagName('img');images[0].src.toString();"];
    NSString *imageUrls = [self.webView stringByEvaluatingJavaScriptFromString:@"var images= document.getElementsByTagName('img');var imageUrls = "";for(var i = 0; i < images.length; i++){var image = images[i];imageUrls += image.src;imageUrls += \\’,\\’;}imageUrls.toString();"];
    NSLog(@"firstUrl : %@", firstImageUrl);
    NSLog(@"images : %@",imageUrls);
}

第一个NSLog返回了正确的结果,但是第二个NSLog返回空:

2013-01-25 00:51:23.253 WebDemo[3416:907] firstUrl: https://www.paypalobjects.com/en_US/i/scr/pixel.gif
2013-01-25 00:51:23.254 WebDemo[3416:907] images :

不知道问题出在哪儿了,请高手指点。

在加载的webview html源码中运行一个正则表达式来实现:

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
  static NSString *CellId = @"Cell";

  Cell *cell=[table dequeueReusableCellWithIdentifier:CellId];
  if (cell==nil) {
      [[NSBundle mainBundle]loadNibNamed:@"Cell" owner:self options:nil];
      cell=self.custom;
  }
  // Get the event corresponding to the current index path and configure the table view cell.
  Student *stu = (Student *)[dataarr objectAtIndex:indexPath.row];
  cell.item.text = [stu name];
  cell.rate.text = [stu rate];
  currentindex=indexPath.row;
  return cell;
}

这是个基本的正则表达式,需要根据图片属性添加一些别的细节。

NSString *imageUrls = [_webView stringByEvaluatingJavaScriptFromString:@"var str=new Array();"
"$('img').each(function(){str.push($(this).attr('src'));});"
"str.join(',');"];
NSLog(@"images : %@",imageUrls);

@"var images= document.getElementsByTagName('img');var imageUrls = "";for(var i = 0; i < images.length; i++){var image = images[i];imageUrls += image.src;imageUrls += \’,\’;}imageUrls.toString();"

这个语句里面的 var imageUrls="";, 在OC语言里面,会把这个当做前后两个分开写的字符串,会合在一起,就是在C语言中, "abc" "def" 和 "abcdef"是完全相同的字符串,var imageUrls=""; 也就是相当于写成了 var imageUrls=;这是有错误的,应该将这个引号进行转义就OK了

static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i<objs.length;i++){\
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";