爬虫之福利抓图爬虫

#! /usr/bin/env python
#coding=utf-8
# encoding=utf-8

import sys
import urllib
from bs4 import BeautifulSoup
import os
reload(sys)
sys.setdefaultencoding('utf-8')
debug = True # 设置是否打印log
def log(message):
    if debug:
        print message.encode('gbk')


def download_image(url, save_path):
    '''根据图片url下载图片到save_path '''
    try:
        urllib.urlretrieve(url, save_path)
        log('Downloaded a image: ' + save_path)
    except Exception, e:
        #print 'An error catched when download a image:', e
        #print url
        url = "http://qiubaichengren.com/"+url
        #print url
        urllib.urlretrieve(url, save_path)
        log('Downloaded a image: ' + save_path)


def load_page_html(url):

    ''' 得到页面的HTML文本 '''
    log('Get a html page : '+ url)
    return urllib.urlopen(url).read()


def down_page_images(page, save_dir):
    '''下载第page页的图片'''
    html_context = load_page_html('http://qiubaichengren.com/%d.html' % page)
    soup = BeautifulSoup(html_context,'html.parser')
    for ui_module_div in soup.findAll('div', {'class': 'ui-module'}):
        img_tag = ui_module_div.find('img')
        if img_tag is not None and img_tag.has_attr('alt') and img_tag.has_attr('src'):
            alt = img_tag.attrs['alt'] # 图片的介绍
            src = img_tag.attrs['src'] # 图片的地址
            filename = '%s%s' % (alt, src[-4:]) # 取后四位(有的图片后缀是'.jpg'而有的是'.gif')
            dst = save_dir + filename
            if not os.path.exists(dst):
                download_image(src, save_dir + filename)


def download_qbcr(frm=1, page_count=3, save_dir='./'):
    for x in xrange(frm, frm + page_count):
        log('Page : ' + `x`)
        down_page_images(x, save_dir)

def main(frm,page_count):
    base_path = 'D:\'
    download_qbcr(frm, page_count, save_dir=base_path)

if __name__ == '__main__':
    print "****福利爬虫****".encode('gbk')
    frm = int(raw_input("开始页为:".encode('gbk')))
    page_count =int(raw_input("增量页为:".encode('gbk')))
    main(frm,page_count)



Categories: Python, 爬虫

发表评论 取消回复

电子邮件地址不会被公开。 必填项已用*标注

姓名 *

站点

评论

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cpongo11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值