zoukankan      html  css  js  c++  java
  • 简单爬虫-爬贴吧图片

    #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)

    百度图片爬虫

    #!/usr/bin/env python 
    #-*- coding:utf-8 -*-
    import re
    import requests
    
    def dowmloadPic(html,keyword):
    
    
        pic_url = re.findall('"objURL":"(.*?)",',html,re.S)
        i = 0
        print '找到关键词:'+keyword+'的图片,现在开始下载图片...'
        for each in pic_url:
            print '正在下载第'+str(i+1)+'张图片,图片地址:'+str(each)
            try:
                pic= requests.get(each, timeout=10)
            except requests.exceptions.ConnectionError:
                print '【错误】当前图片无法下载'
                continue
            string = '/home/adonis/picture'+keyword+'_'+str(i) + '.jpg'
            #resolve the problem of encode, make sure that chinese name could be store
            fp = open(string.decode('utf-8').encode('cp936'),'wb')
            fp.write(pic.content)
            fp.close()
            i += 1
    
    
    
    if __name__ == '__main__':
        word = raw_input("Input key word: ")
        url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word='+word+'&ct=201326592&v=flip'
        result = requests.get(url)
        dowmloadPic(result.text,word)
  • 相关阅读:
    2. 商城项目完整购物链路 lq
    如何看源码? lq
    事务的了解 lq
    1. 商城业务架构分析 lq
    并发的基础知识 lq
    mysql 索引 lq
    mysqlinnodb了解 lq
    IE6.0、IE7.0 与FireFox CSS兼容的解决方法
    CSS:html/css教程:背景图片的定位问题详解
    IE6 BUG
  • 原文地址:https://www.cnblogs.com/wangtao1993/p/6683475.html
Copyright © 2011-2022 走看看