Python 爬取蜂鸟网的照片

初衷

上次兔子君问 如何下载 蜂鸟网 上图集的一张照片。打开之后,确实无法右键另存为。不应该啊,web上面还没有这么强的技术保护发布的图片。firebug查看,图片的搜索总是指向一个 a标签。这个 a 标签有一个 height:100%。应该是一个遮罩,用来给幻灯片浏览导航使用的。无意中也进行了简单的 盗图保护。

下载很简单,不过兔子先生的需求有变,需要下载一个图集,这样右键的行为,显然比较累。唔,想要下载一个图集,写脚本 爬虫了。爬一个图集下来,python这方面是好手。               

分析

分析页面,每一个图集并不是 ajax 取照片,而是每一张照片一个页面。并且页面的URL地址很规律,某个值依次加一。例如        这个图集的所有照片:

http://travel.fengniao.com/slide/334/3344576_1.html#show 

http://travel.fengniao.com/slide/334/3344576_2.html#show 

都是 3344576_1, 3344576_2有变动,每一图都在一个特有的 img标签里。如下图:

问题的解决思路有了,用 python的 urllib2模块打开 url,这些 url 依次递增1,用 list 解析给 urllib2模块。当得到 web的html之后,再用 BeautifulSoup 解析文档,提取 img 的 url。

主要用到了 urllib2 的urlopen方法,和  BeautifulSoup 的findAll方法和 tag对象获取属性的方法。

#!/usr/bin/python
# -*- coding: utf-8 -*-
# target url
# http://travel.fengniao.com/slide/334/3344576_%d.html
# target picture
# <img src="http://img2.zol.com.cn/product/101/538/ceDuLihKRGmck.png" name="img_share" id="mainPic" width="449" height="636" alt="">
                                          
import urllib2
from BeautifulSoup import BeautifulSoup
      
urlList = 'http://travel.fengniao.com/slide/334/3344576_1.html'
html = urllib2.urlopen(urlList)
soup = BeautifulSoup(html)
imgsResult = soup.findAll('img',id="mainPic")
print imgsResult[0]['src']


"""
# time python image.py 
http://img2.zol.com.cn/product/101/538/ceDuLihKRGmck.png


real    0m15.562s
user    0m0.103s
sys     0m0.104s
"""


# get the url of web which has the picture =>url results
urlList = ['http://travel.fengniao.com/slide/334/3344576_%d.html' % i for i in range(1,40)]
imgurl = []
# open every url via urllib2,get the img tag via BeautifulSoup
for i in urlList:
	#print i
    html = urllib2.urlopen(i)
    soup = BeautifulSoup(html)
    imgsResult = soup.findAll('img',id="mainPic")
    imgurl.append(imgsResult[0]['src'])
                                           
# the result
print imgurl


你可能感兴趣的:(python,爬虫)