python爬取NUS-WIDE数据库图片

yipeiwu_com5年前Python爬虫

实验室需要NUS-WIDE数据库中的原图,数据集的地址为http://lms.comp.nus.edu.sg/research/NUS-WIDE.htm   由于这个数据只给了每个图片的URL,所以需要一个小爬虫程序来爬取这些图片。在图片的下载过程中建议使用VPN。由于一些URL已经失效,所以会下载一些无效的图片。

# PYTHON 2.7   Ubuntu 14.04
nuswide = "$NUS-WIDE-urls_ROOT" #the location of your nus-wide-urls.txt
imagepath = "$IMAGE_ROOT" # path of dataset you want to download in
f = open(nuswide, 'r')
url = f.readlines()
import re
import urllib
import os
reg = r"ImageData.+?jpg"
location_re = re.compile(reg)
reg = r"(ImageData.+?)/0"
direction_re = re.compile(reg)
reg = r"http.+?jpg"
image_re = re.compile(reg)
for i in url:
  filename = re.findall(location_re, i)
  direction = re.findall(direction_re, i)
  image = re.findall(image_re, i)
  if image:
    path = imagepath+filename[0]
    path_n = imagepath+direction[0]
    print path_n
    if os.path.exists(path_n):
      urllib.urlretrieve(image[1], path)
    else:
      os.makedirs(path_n)
      urllib.urlretrieve(image[1], path)

再给大家分享一个爬取百度贴吧图片的小爬虫(你懂得)

#coding=utf-8

#urllib模块提供了读取Web页面数据的接口
import urllib
#re模块主要包含了正则表达式
import re
#定义一个getHtml()函数
def getHtml(url):
  page = urllib.urlopen(url) #urllib.urlopen()方法用于打开一个URL地址
  html = page.read() #read()方法用于读取URL上的数据
  return html

def getImg(html):
  reg = r'src="(.+?\.jpg)" pic_ext'  #正则表达式,得到图片地址
  imgre = re.compile(reg)   #re.compile() 可以把正则表达式编译成一个正则表达式对象.
  imglist = re.findall(imgre,html)   #re.findall() 方法读取html 中包含 imgre(正则表达式)的  数据
  #把筛选的图片地址通过for循环遍历并保存到本地
  #核心是urllib.urlretrieve()方法,直接将远程数据下载到本地,图片通过x依次递增命名
  x = 0

  for imgurl in imglist:
  urllib.urlretrieve(imgurl,'D:\E\%s.jpg' % x)
      x+=1


html = getHtml("http://tieba.baidu.com/p/xxxx")
print getImg(html)

相关文章

Python 3实战爬虫之爬取京东图书的图片详解

Python 3实战爬虫之爬取京东图书的图片详解

前言 最近工作中遇到一个需求,需要将京东上图书的图片下载下来,假如我们想把京东商城图书类的图片类商品图片全部下载到本地,通过手工复制粘贴将是一项非常庞大的工程,此时,可以用Python网...

浅谈Python爬取网页的编码处理

浅谈Python爬取网页的编码处理

背景 中秋的时候,一个朋友给我发了一封邮件,说他在爬链家的时候,发现网页返回的代码都是乱码,让我帮他参谋参谋(中秋加班,真是敬业= =!),其实这个问题我很早就遇到过,之前在爬小说的时候...

浅谈Scrapy网络爬虫框架的工作原理和数据采集

浅谈Scrapy网络爬虫框架的工作原理和数据采集

今天小编给大家详细的讲解一下Scrapy爬虫框架,希望对大家的学习有帮助。 1、Scrapy爬虫框架 Scrapy是一个使用Python编程语言编写的爬虫框架,任何人都可以根据自己的需求...

python抓取豆瓣图片并自动保存示例学习

环境Python 2.7.6,BS4,在powershell或命令行均可运行。请确保安装了BS模块复制代码 代码如下:# -*- coding:utf8 -*-# 2013.12.36...

python爬虫 爬取58同城上所有城市的租房信息详解

python爬虫 爬取58同城上所有城市的租房信息详解

代码如下 from fake_useragent import UserAgent from lxml import etree import requests, os import...