# -*- coding: utf-8 -*-

 import json
import os
import time
from multiprocessing import Pool
import multiprocessing
import requests
from selenium import webdriver def get_image_links(keyword, num_requested = 1000):
"""get image links with selenium
"""
number_of_scrolls = int(num_requested/400) + 1
img_urls = set()#设置为集合,自动去除重复链接
chrome_options = webdriver.ChromeOptions()
# chrome_options.add_argument('--headless')#设置无头浏览器
# chrome_options.add_argument('user-agent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"')
# chrome_options.add_argument("lang=en_US")#设置语言
# prefs = {"profile.managed_default_content_settings.images":2}
# chrome_options.add_experimental_option("prefs",prefs)#配置不加载图片
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.maximize_window()
search_query = keyword
url = "https://www.google.com/search?q="+search_query+"&source=lnms&tbm=isch"
driver.get(url)
for _ in range(number_of_scrolls):
for i in range(5):
# multiple scrolls needed to show all 400 images
driver.execute_script("window.scrollBy(0, 100000)")
time.sleep(1)
time.sleep(5)#等待页面刷新,否则有可能元素不可见
try:
# driver.find_element_by_xpath("//input[@value='Show more results']").click()#浏览器的中英文版本不同
driver.find_element_by_xpath("//input[@value='显示更多结果']").click()
except Exception as e:
print("reach the end of page ")
break # with open('page.html','w') as f:
# f.write(driver.page_source)
imgs = driver.find_elements_by_xpath('//div[contains(@class,"rg_meta")]')#模糊定位
for i,img in enumerate(imgs):
img_url = json.loads(img.get_attribute('innerHTML'))["ou"]
img_urls.add(img_url)
driver.quit()
print("finish getting all image urls!") return img_urls def download(urls,download_dir):
'''download images
'''
print("start downloading images!")
for url in urls:
filename=os.path.join(download_dir,os.path.basename(url))
try:
r = requests.get(url, stream=True, timeout=60)
r.raise_for_status()
with open(filename, 'wb') as f:
f.write(r.content)
except Exception:
continue
print("finish downloading images!") keywords = ['girl','boy']
download_dir = './images/'
download_dirs = []
for keyword in keywords:
path = os.path.join(download_dir,keyword)
download_dirs.append(path)
if not os.path.exists(path):
os.makedirs(path) # for keyword in main_keywords:
# image_urls = get_image_links(keyword)
# download(image_urls,download_dir) ###################################
# get image links/MultiProcess
###################################
img_urls=[]
multiprocessing.freeze_support()
p = Pool(4) # default number of process is the number of cores of your CPU, change it by yourself
for keyword in keywords:
img_urls.append(p.apply_async(get_image_links, (keyword,)))
#img_urls:[<multiprocessing.pool.ApplyResult object at 0x7f536925fcc0>, <multiprocessing.pool.ApplyResult object at 0x7f536925fd68>]
for i,urls in enumerate(img_urls):
img_urls[i]=urls.get()
p.close()
p.join() # # ###################################
# # # download images/MultiProcess
# # ###################################
p = Pool(4) # default number of process is the number of cores of your CPU, change it by yourself
for i,urls in enumerate(img_urls):
p.apply_async(download, [urls,download_dirs[i]])
p.close()
p.join()

python+selenium爬取关键字搜索google图片的更多相关文章

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

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

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

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

  3. Python+selenium爬取智联招聘的职位信息

    整个爬虫是基于selenium和Python来运行的,运行需要的包 mysql,matplotlib,selenium 需要安装selenium火狐浏览器驱动,百度的搜寻. 整个爬虫是模块化组织的,不 ...

  4. Python 爬虫 爬取 煎蛋网 图片

    今天, 试着爬取了煎蛋网的图片. 用到的包: urllib.request os 分别使用几个函数,来控制下载的图片的页数,获取图片的网页,获取网页页数以及保存图片到本地.过程简单清晰明了 直接上源代 ...

  5. python+selenium爬取百度文库不能下载的word文档

    有些时候我们需要用到百度文库的某些文章时,却发现需要会员才能下载,很难受,其实我们可以通过爬虫的方式来获取到我们所需要的文本. 工具:python3.7+selenium+任意一款编辑器 前期准备:可 ...

  6. 爬虫之selenium爬取斗鱼主播图片

    这是我GitHub上简单的selenium介绍与简单使用:https://github.com/bwyt/spider/tree/master/selenium%E5%9F%BA%E7%A1%80 & ...

  7. python selenium 爬取淘宝

    # -*- coding:utf-8 -*- # author : yesehngbao # time:2018/3/29 import re import pymongo from lxml imp ...

  8. python selenium爬取QQ空间方法

    from selenium import webdriver import time # 打开浏览器 dr = webdriver.Chrome() # 打开某个网址 dr.get('https:// ...

  9. python selenium爬取自如租房数据保存到TXT文件

    # -*- coding: utf-8 -*-"""Created on Fri Aug 31  2018 @author: chenlinlab"" ...

随机推荐

  1. NFV实验平台

    NFV架构如下图所示. NFVI对应于数据平面,数据平面转发数据并提供用于运行网络服务的资源. MANO对应于控制平面,该控制平面负责构建各种VNF之间的连接以及编排NFVI中的资源. VNF层对应于 ...

  2. python练习:寒冰猴子狐狸,猫狗咬架

    python练习:寒冰猴子狐狸,猫狗咬架 一,寒冰猴子狐狸 class Person: def __init__(self, na, gen, age, fig): self.name = na se ...

  3. flask 实现最简单的登录功能

    视图函数如下: # Sample.py from flask import Flask, render_template, url_for, request, redirect app = Flask ...

  4. (转)关于sql和MySQL的语句执行顺序(必看!!!)

    原文:https://blog.csdn.net/u014044812/article/details/51004754 https://blog.csdn.net/j080624/article/d ...

  5. 数据分析入门——pandas之数据合并

    主要分为:级联:pd.concat.pd.append 合并:pd.merge 一.numpy级联的回顾 详细参考numpy章节 https://www.cnblogs.com/jiangbei/p/ ...

  6. GCC版本中没有GLIBCXX_3.4.15错误

    解决错误呈现该错误的原因是当前的GCC版本中,没有GLIBCXX_3.4.15,须要安装更高版本.我们可以输入:strings /usr/lib64/libstdc++.so.6 | grep GLI ...

  7. 【交互】抖音VS快手

    从能量节约,懒惰的人性本质角度来分析,有点意思. https://www.ui.cn/detail/506135.html

  8. iOS @功能的部分实现思路

    需求描述 1. 发布信息时,通过键盘键入@符号,或者点选相关功能键,唤醒@列表,进行选择 2.选择结束后,输入栏改色显示相关内容 3.删除时,整体删除@区块,且不能让光标落在@区块之间 实现步骤 1. ...

  9. python实践项目七:正则表达式版本的strip()函数

    描述:写一个函数,它接受一个字符串,做的事情和 strip()字符串方法一样.如果只传入了要去除的字符串, 没有其他参数, 那么就从该字符串首尾去除空白字符:否则, 函数第二个参数指定的字符将从该字符 ...

  10. python实践项目六:正则表达式-强口令

    描述:写一个函数,它使用正则表达式,确保传入的口令字符串是强口令.强口令的定义是:长度不少于8 个字符,  同时包含大写和小写字符, 至少有一位数字. 代码: #!/usr/bin/python # ...