前言:
作为一名从小就看篮球的球迷,会经常逛虎扑篮球及湿乎乎等论坛,在论坛里面会存在很多精美图片,包括NBA球队、CBA明星、花边新闻、球鞋美女等等,如果一张张右键另存为的话真是手都点疼了。作为程序员还是写个程序来进行吧!
所以我通过Python+Selenium+正则表达式+urllib2进行海量图片爬取。
运行效果:
http://photo.hupu.com/nba/tag/马刺
http://photo.hupu.com/nba/tag/陈露
源代码:
# -*- coding: utf-8 -*- """ Crawling pictures by selenium and urllib url: 虎扑 马刺 http://photo.hupu.com/nba/tag/%E9%A9%AC%E5%88%BA url: 虎扑 陈露 http://photo.hupu.com/nba/tag/%E9%99%88%E9%9C%B2 Created on 2015-10-24 @author: Eastmount CSDN """ import time import re import os import sys import urllib import shutil import datetime from selenium import webdriver from selenium.webdriver.common.keys import Keys import selenium.webdriver.support.ui as ui from selenium.webdriver.common.action_chains import ActionChains #Open PhantomJS driver = webdriver.PhantomJS(executable_path="G:phantomjs-1.9.1-windowsphantomjs.exe") #driver = webdriver.Firefox() wait = ui.WebDriverWait(driver,10) #Download one Picture By urllib def loadPicture(pic_url, pic_path): pic_name = os.path.basename(pic_url) #删除路径获取图片名字 pic_name = pic_name.replace('*','') #去除'*' 防止错误 invalid mode ('wb') or filename urllib.urlretrieve(pic_url, pic_path + pic_name) #爬取具体的图片及下一张 def getscript(elem_url, path, nums): try: #由于链接 http://photo.hupu.com/nba/p29556-1.html #只需拼接 http://..../p29556-数字.html 省略了自动点击"下一张" *** 作 count = 1 t = elem_url.find(r'.html') while (count <= nums): html_url = elem_url[:t] + '-' + str(count) + '.html' #print html_url ''' driver_pic.get(html_url) elem = driver_pic.find_element_by_xpath("//div[@class='pic_bg']/div/img") url = elem.get_attribute("src") ''' #采用正则表达式获取第3个 再获取图片URL进行下载 content = urllib.urlopen(html_url).read() start = content.find(r'') end = content.find(r'') content = content[start:end] div_pat = r'(.*?)欢迎分享,转载请注明来源:内存溢出
评论列表(0条)