小赖子的英国生活和资讯

通过 PHPQuery 抓取 Tumblr 3000 多张图片

阅读 桌面完整版

Tumblr 上的很多图片都很不错 特别是一些精选的图片. 可以通过 Tumblr API 来进行爪取. 也可以直接网页抓. PHP有一个库叫 PHPQuery, 也就是把 JQuery 的方式引起到PHP里, 让PHP也支持通过 CSS 选择器的方式对页面元素进行搜索.

phpquery 通过 PHPQuery 抓取 Tumblr 3000 多张图片 I.T. PHP是最好的语言 互联网 技术 折腾

phpquery

通过 PHPQuery, 抓取 变得极为简单. Click To Tweet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
require('phpQuery.php');
require('app.php');
 
$ip = get_ip_address();
 
function grab($url, $lvl = 5) {
  global $ip;
  if ($lvl < = 0) {
    return;
  }
  $doc = phpQuery::newDocumentFile($url);
  foreach(pq('div.TumbPostPane') as $p) {
      $img = pq($p)->find('img.PhotoPostMainPhoto')->attr('src');
      $desc = htmlspecialchars(trim(pq($p)->find('div.MetaPanel')->html()));
      $url = pq($p)->find('a')->attr('href');
      $err = '';
      if (UploadPic($img, $desc, $err, $ip)) { // 发现并下载保存图片
         echo "OK = $err \n";
      } else {
         echo str_replace("<br />", "\n", "Error = $err \n");
      }     
      grab($url, $lvl - 1); // 递归抓取
  }
}
 
grab("https://uploadbeta.com", 1); 
require('phpQuery.php');
require('app.php');

$ip = get_ip_address();

function grab($url, $lvl = 5) {
  global $ip;
  if ($lvl < = 0) {
    return;
  }
  $doc = phpQuery::newDocumentFile($url);
  foreach(pq('div.TumbPostPane') as $p) {
      $img = pq($p)->find('img.PhotoPostMainPhoto')->attr('src');
      $desc = htmlspecialchars(trim(pq($p)->find('div.MetaPanel')->html()));
      $url = pq($p)->find('a')->attr('href');
      $err = '';
      if (UploadPic($img, $desc, $err, $ip)) { // 发现并下载保存图片
         echo "OK = $err \n";
      } else {
         echo str_replace("<br />", "\n", "Error = $err \n");
      }     
      grab($url, $lvl - 1); // 递归抓取
  }
}

grab("https://uploadbeta.com", 1); 

以上代码只需要稍做修改就可以用了. 几分钟 就下载了 3000多张图片. 图片都下载到自己的VPS服务器上 并且有相应的图片介绍. 具体效果请看: uploadbeta.com

当然抓取的频率不要太大 要不然很有可能被封 IP 地址 了 最好抓取有个时间间隔 比如几十毫秒.

抓取 图片

另: 图片网站支持各类 API 方便大家使用: https://uploadbeta.com/picture-gallery/faq.php#api

英文: https://helloacm.com/case-study-use-phpquery-to-crawl-3000-images-from-tumblr/

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version