1、根据搜索词下载百度图片:

# -*- coding: utf-8 -*-
"""根据搜索词下载百度图片"""
import re
import sys
import urllib import requests def get_onepage_urls(onepageurl):
"""获取单个翻页的所有图片的urls+当前翻页的下一翻页的url"""
if not onepageurl:
print('已到最后一页, 结束')
return [], ''
try:
html = requests.get(onepageurl)
html.encoding = 'utf-8'
html = html.text
except Exception as e:
print(e)
pic_urls = []
fanye_url = ''
return pic_urls, fanye_url
pic_urls = re.findall('"objURL":"(.*?)",', html, re.S)
fanye_urls = re.findall(re.compile(r'<a href="(.*)" class="n">下一页</a>'), html, flags=0)
fanye_url = 'http://image.baidu.com' + fanye_urls[0] if fanye_urls else ''
return pic_urls, fanye_url def down_pic(pic_urls):
"""给出图片链接列表, 下载所有图片"""
for i, pic_url in enumerate(pic_urls):
try:
pic = requests.get(pic_url, timeout=15)
string = str(i + 1) + '.jpg'
with open(string, 'wb') as f:
f.write(pic.content)
print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
except Exception as e:
print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
print(e)
continue if __name__ == '__main__':
keyword = '火车票' # 关键词, 改为你想输入的词即可, 相当于在百度图片里搜索一样
url_init_first = r'http://image.baidu.com/search/flip?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1497491098685_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&ctd=1497491098685%5E00_1519X735&word='
url_init = url_init_first + urllib.parse.quote(keyword, safe='/')
all_pic_urls = []
onepage_urls, fanye_url = get_onepage_urls(url_init)
all_pic_urls.extend(onepage_urls) fanye_count = 0 # 累计翻页数
while 1:
onepage_urls, fanye_url = get_onepage_urls(fanye_url)
fanye_count += 1
# print('第页' % str(fanye_count))
if fanye_url == '' and onepage_urls == []:
break
all_pic_urls.extend(onepage_urls) down_pic(list(set(all_pic_urls)))

链接:https://blog.csdn.net/xiligey1/article/details/73321152  

2、根据搜索词下载谷歌、必应、百度图片

# coding:utf-8
# 基于icrawler第三方库同时爬取google,baidu,bing图片,并对名称进行重写,数据进行分类
# 图片存放路径为:base_dir='F:/文档/text' import logging
import sys
import base64
from datetime import date
from icrawler.builtin import BaiduImageCrawler, BingImageCrawler, GoogleImageCrawler
from icrawler import ImageDownloader
from icrawler.builtin import GoogleImageCrawler
from six.moves.urllib.parse import urlparse class PrefixNameDownloader(ImageDownloader): def get_filename(self, task, default_ext):
filename = super(PrefixNameDownloader, self).get_filename(
task, default_ext)
return 'prefix_' + filename class Base64NameDownloader(ImageDownloader): def get_filename(self, task, default_ext):
url_path = urlparse(task['file_url'])[2]
if '.' in url_path:
extension = url_path.split('.')[-1]
if extension.lower() not in [
'jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif', 'ppm', 'pgm'
]:
extension = default_ext
else:
extension = default_ext
filename = base64.b64encode(url_path.encode()).decode()
return '{}.{}'.format(filename, extension) def test_google(dir,keyword):
print('启用google爬虫')
google_crawler = GoogleImageCrawler(parser_threads=20,
downloader_threads=20,
downloader_cls=Base64NameDownloader,
storage={'root_dir': dir},
log_level = logging.INFO)
google_crawler.crawl(keyword=keyword, offset=0, max_num=1000,min_size=(200,200), max_size=None) def test_bing(dir,keyword):
keyword = keyword.replace(': flickr.com', '')
print('启用bing爬虫',keyword)
bing_crawler = BingImageCrawler(
# parser_threads=16,
downloader_cls=Base64NameDownloader,
downloader_threads=16,
storage={'root_dir': dir},
log_level=logging.DEBUG)
bing_crawler.crawl(keyword=keyword,offset=0, max_num=1000,min_size=None,max_size=None) def test_baidu(dir,keyword):
keyword = keyword.replace(': flickr.com', '')
print('启用百度爬虫',keyword)
baidu_crawler = BaiduImageCrawler(
# parser_threads=16,
# downloader_threads=16,
downloader_cls=Base64NameDownloader,
storage={'root_dir': dir},
log_level = logging.DEBUG)
baidu_crawler.crawl(keyword=keyword, offset=0,max_num=1000,min_size=None,max_size=None) def main():
##################################################################
keyword='火车票'
base_dir='F:/文档/text'
if len(sys.argv) == 1:
dst = 'all'
else:
dst = sys.argv[1:]
if 'all' in dst:
dst = ['google', 'bing', 'baidu',]
if 'google' in dst:
test_google(base_dir,keyword)
if 'bing' in dst:
test_bing(base_dir,keyword)
if 'baidu' in dst:
test_baidu(base_dir,keyword) if __name__ == '__main__':
main()

  

链接:https://github.com/Crawler-y/Image_crawl-

3、github 搜索爬虫,有许多有趣的项目。

python 火车票爬取代码的更多相关文章

  1. 使用python scrapy爬取知乎提问信息

    前文介绍了python的scrapy爬虫框架和登录知乎的方法. 这里介绍如何爬取知乎的问题信息,并保存到mysql数据库中. 首先,看一下我要爬取哪些内容: 如下图所示,我要爬取一个问题的6个信息: ...

  2. 大神:python怎么爬取js的页面

    大神:python怎么爬取js的页面 可以试试抓包看看它请求了哪些东西, 很多时候可以绕过网页直接请求后面的API 实在不行就上 selenium (selenium大法好) selenium和pha ...

  3. python连续爬取多个网页的图片分别保存到不同的文件夹

      python连续爬取多个网页的图片分别保存到不同的文件夹 作者:vpoet mail:vpoet_sir@163.com #coding:utf-8 import urllib import ur ...

  4. python定时器爬取豆瓣音乐Top榜歌名

    python定时器爬取豆瓣音乐Top榜歌名 作者:vpoet mail:vpoet_sir@163.com 注:这些小demo都是前段时间为了学python写的,现在贴出来纯粹是为了和大家分享一下 # ...

  5. python大规模爬取京东

    python大规模爬取京东 主要工具 scrapy BeautifulSoup requests 分析步骤 打开京东首页,输入裤子将会看到页面跳转到了这里,这就是我们要分析的起点 我们可以看到这个页面 ...

  6. Python爬虫 - 爬取百度html代码前200行

    Python爬虫 - 爬取百度html代码前200行 - 改进版,  增加了对字符串的.strip()处理 源代码如下: # 改进版, 增加了 .strip()方法的使用 # coding=utf-8 ...

  7. python scrapy爬取知乎问题和收藏夹下所有答案的内容和图片

    上文介绍了爬取知乎问题信息的整个过程,这里介绍下爬取问题下所有答案的内容和图片,大致过程相同,部分核心代码不同. 爬取一个问题的所有内容流程大致如下: 一个问题url 请求url,获取问题下的答案个数 ...

  8. Python+Selenium爬取动态加载页面(2)

    注: 上一篇<Python+Selenium爬取动态加载页面(1)>讲了基本地如何获取动态页面的数据,这里再讲一个稍微复杂一点的数据获取全国水雨情网.数据的获取过程跟人手动获取过程类似,所 ...

  9. Python+Selenium爬取动态加载页面(1)

    注: 最近有一小任务,需要收集水质和水雨信息,找了两个网站:国家地表水水质自动监测实时数据发布系统和全国水雨情网.由于这两个网站的数据都是动态加载出来的,所以我用了Selenium来完成我的数据获取. ...

随机推荐

  1. Spring注入日期到bean属性-CustomDateEditor

    这一个Spring例子向您展示如何为bean属性注入一个“日期”. package com.yiibai.common; import java.util.Date; public class Cus ...

  2. Android开发:ListView加上长按事件

    为ListView加上长按事件 lvMain.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public b ...

  3. IIS发布站点错误收集

    转载:http://www.cnblogs.com/hangwei/p/4249406.html 本文主要收集IIS在发布站点过程中遇到的错误,并提供解决办法.并亲测可行.如果您也在使用IIS发布站点 ...

  4. Ant:Ant 入门

    背景 自从有了 Maven 以后,Ant 视乎就不流行了,不过 Ant 还是有其应用场景的,Ant 的思想比较简洁,如下: 一个 project 包含多个 target(类似成员方法). 一个 tar ...

  5. GO语言 -- 调用DLL函数,填平所有的坑,最详尽攻略

    编译dll文件(源代码c++):g++ -shared main.cpp -o test.dll set GOARCH=386 第一个DLL函数,第一个参数,要求传入一个指针,直接指向[]byte类型 ...

  6. windows10 Sqlserver卸载 指定账户不存在

    在windows卸载程序时,有时会出现因提示“指定的账户不存在”而无法删除,如下: 这时时候要先选择要删除的项目,进行修复后再进行删除就可以正常删除了

  7. (顺序表应用5.1.1)POJ 3750 小孩报数问题(基本的约瑟夫环问题:给出人数n,出发位置w,间隔数s)

    /* * POJ_3750.cpp * * Created on: 2013年10月30日 * Author: Administrator */ #include <iostream> # ...

  8. RS查询报错之递归公用表表达式不包含顶级 UNION ALL运算符

    在FM里面涉及模型的时候,修改了物理层的查询SQL如下 select * from TARGET_VISIT_GH where ghksdm in(select dept_id from DIM_BI ...

  9. github 排名前100的项目

    dotnet/roslyn The .NET Compiler Platform ("Roslyn") provides open-source C# and Visual Bas ...

  10. (linux shell)第二章--命令之乐(一)

    文章来自于我的个人博客:(linux shell)第二章--命令之乐(一)    上一章我们描写叙述了一些linux shell中须要注意的一些语法.接下来我们開始了解linux shell的经常使用 ...