基于Python的网页图片爬虫

两个爬虫代码参考了多篇资料,若有需要标注,请私信联系。闲言少叙,直接上代码。

# -*- coding:utf-8 -*-
import re
import requests

def dowmloadPic(html, keyword):
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
    i = 1
    print('找到关键词:' + keyword + '的图片,现在开始下载图片...')
    for each in pic_url:
        print('正在下载第' + str(i) + '张图片,图片地址:' + str(each))
        try:
            pic = requests.get(each, timeout=10)
            # requests.adapters.DEFAULT_RETRIES = 5
        except requests.exceptions.ConnectionError:
            print('【错误】当前图片无法下载')
            continue

        dir = '../images/' + keyword + '_' + str(i) + '.jpg'
        fp = open(dir, 'wb')
        fp.write(pic.content)
        fp.close()
        i += 1
        s = requests.session()
        s.keep_alive = False


if __name__ == '__main__':
    word = input("Input key word: ")
    # pageId = 0
    # # 这里我保存到第50页
    # for i in range(50):
    #     url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + "&pn=" + str(
    #         pageId) + "&gsm=?&ct=&ic=0&lm=-1&width=0&height=0"
    #     pageId += 20
    url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&ct=201326592&v=flip'

    # url = 'http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=' + word
    result = requests.get(url)
    dowmloadPic(result.text, word)


上面这个版本适用于download打开的一个页面,不会自动滚动下滑条。

# -*- coding:utf-8 -*-
import re
import requests
import traceback
import os


def dowmloadPic(html, keyword, startNum):
    kv = {'user-agent': 'Mozilla/5.0'}
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
    num = len(pic_url)
    i = startNum
    root = 'L:/pics/'
    print('找到关键词:' + keyword + '的图片,现在开始下载图片...')

    for each in pic_url:
        print('正在下载第' + str(i + 1) + '张图片,图片地址:' + str(each))
        path = root + each.split('/')[-1]
        # dir = root + keyword + str(i) + '.jpg'
        dir = root + keyword + 'v1_' + str(i) + '.jpg'
        try:
            if not os.path.exists(root):
                os.mkdir(root)
            if not os.path.exists(path):
                pic = requests.get(each, headers=kv, timeout=10)
                with open(dir, 'wb') as f:
                    f.write(pic.content)
                    f.close()

        except:
            traceback.print_exc()
            print('【错误】当前图片无法下载')
            continue
        i += 1

    return i


if __name__ == '__main__':

    kv = {'user-agent': 'Mozilla/5.0'}
    lastNum = 0
    words = ['篮球','排球']
    # words为一个列表,可以自动保存多个关键字的图片
    for word in words:
        # word = input("Input key word: ")
        if word.strip() == "exit":
            break
        pageId = 0
        # 此处的参数为需爬取的页数
        for i in range(10):
            url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + "&pn=" + str(
                pageId) + "&gsm=?&ct=&ic=0&lm=-1&width=0&height=0"
            pageId += 20
            result = requests.get(url, headers=kv)
            lastNum = dowmloadPic(result.text, word, lastNum)

上面这个版本适用于可以滚动下滑条,download大量图片。

向IT工作者致敬,后丹之喜碧CatBrother欢迎吐槽:
后丹-喜碧CatBrother

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 爬虫 本项目依赖Python的BeautifulSoup4第三方库,使用本项目需要先安装BeautifulSoup4。 步骤一 安装依赖库: 安装BeautifulSoup4: 1.Debain或Ubuntu可以通过系统软件包管理安装 $sudo apt-get install Python-bs4 2.使用easy_install或者pip安装: $ sudo easy_install beautifulsoup4 或$ sudo pip install beautifulsoup4 easy_install和pip是Python的发行包管理工具,同样需要先安装才能使用,这里介绍easy_install的安装方法: 1.Mac OS X 系统可以在终端执行以下命令: curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python 2.Linux系统可以执行以下命令: wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python 3.Window系统: 下载ez_setup.py并运行 步骤二 运行: 运行sexy.py文件爬取网站一: 1.不带参数运行:直接运行sexy.py,使用默认配置参数。 2.可用参数: -s 或 --startpage :起始扫描页面,默认值为1,从第一页开始扫描 -e 或 --endpage :最后扫描页面,默认值为65589。 -d 或 --dir :相对当前文件,下载图片保存位置,默认为sexy_images文件夹 -m 或 --max :获取页面失败后最大重试次数,默认为3 -n 或 --new :只获取最新更新的图片,强制设置起始扫描页为1,获取完毕后自动退出 例子:Sexy$ ./sexy.py -s 10 -e 12 -d cache -m 3 表示从第10页开始扫描到第12页,图片保存文件夹为cache,获取页面失败最多可以尝试3次。 3.运行期间可以随时按回车键退出程序。 运行atlas.py文件爬取网站二: 1.不带参数运行:直接运行atlas.py,使用默认配置参数,从主页开始爬取。 2.可用参数: -d 或 --dir :相对当前文件,下载图片保存位置,默认为atlas_images文件夹 -m 或 --max :获取页面失败后最大重试次数,默认为3 -v 或 --view :查看当前已知标签和标签id -t 或 --tag :爬取指定标签名的图片,同时提供标签id时,本标签无效 -i 或 --id :爬取指定标签id的图片 -l 或 --last :是否从上次退出的地方继续爬取,默认为false 3.运行过程中可以随时按Ctrl+C退出,退出时如果还有新发现标签没有归类,归类后自动退出。 4.setting文件中为已归类标签和最后抓取位置缓存,请勿删除。 测试环境: python 2.7 测试通过 License Copyright 2015 Jianan - qinxiandiqi@foxmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值