侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python爬虫系列Selenium定向爬取虎扑篮球图片详解

Python  /  管理员 发布于 7年前   476

前言:

作为一名从小就看篮球的球迷,会经常逛虎扑篮球及湿乎乎等论坛,在论坛里面会存在很多精美图片,包括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 urlliburl: 虎扑 马刺 http://photo.hupu.com/nba/tag/%E9%A9%AC%E5%88%BAurl: 虎扑 陈露 http://photo.hupu.com/nba/tag/%E9%99%88%E9%9C%B2Created 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-windows\phantomjs.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个<div></div> 再获取图片URL进行下载   content = urllib.urlopen(html_url).read()   start = content.find(r'<div class="flTab">')   end = content.find(r'<div class="comMark" style>')   content = content[start:end]   div_pat = r'<div.*?>(.*?)<\/div>'   div_m = re.findall(div_pat, content, re.S|re.M)   #print div_m[2]   link_list = re.findall(r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')", div_m[2])   #print link_list   url = link_list[0] #仅仅一条url链接   loadPicture(url, path)   count = count + 1 except Exception,e:   print 'Error:',e  finally:   print 'Download ' + str(count) + ' pictures\n'    #爬取主页图片集的URL和主题 def getTitle(url):  try:   #爬取URL和标题   count = 0   print 'Function getTitle(key,url)'   driver.get(url)   wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='piclist3']"))  print 'Title: ' + driver.title + '\n'    #缩略图片url(此处无用) 图片数量 标题(文件名) 注意顺序  elem_url = driver.find_elements_by_xpath("//a[@class='ku']/img")  elem_num = driver.find_elements_by_xpath("//div[@class='piclist3']/table/tbody/tr/td/dl/dd[1]")  elem_title = driver.find_elements_by_xpath("//div[@class='piclist3']/table/tbody/tr/td/dl/dt/a")  for url in elem_url:    pic_url = url.get_attribute("src")   html_url = elem_title[count].get_attribute("href")   print elem_title[count].text   print html_url    print pic_url   print elem_num[count].text      #创建图片文件夹   path = "E:\\Picture_HP\\" + elem_title[count].text + "\\"   m = re.findall(r'(\w*[0-9]+)\w*', elem_num[count].text) #爬虫图片张数   nums = int(m[0])   count = count + 1    if os.path.isfile(path):   #Delete file     os.remove(path)    elif os.path.isdir(path):  #Delete dir     shutil.rmtree(path, True)    os.makedirs(path)    #create the file directory    getScript(html_url, path, nums) #visit pages      except Exception,e:   print 'Error:',e  finally:   print 'Find ' + str(count) + ' pages with key\n'   #Enter Function def main():  #Create Folder  basePathDirectory = "E:\\Picture_HP"  if not os.path.exists(basePathDirectory):   os.makedirs(basePathDirectory)   #Input the Key for search str=>unicode=>utf-8  key = raw_input("Please input a key: ").decode(sys.stdin.encoding)  print 'The key is : ' + key   #Set URL List Sum:1-2 Pages  print 'Ready to start the Download!!!\n\n'  starttime = datetime.datetime.now()  num=1  while num<=1:  #url = 'http://photo.hupu.com/nba/tag/%E9%99%88%E9%9C%B2?p=2&o=1'  url = 'http://photo.hupu.com/nba/tag/%E9%A9%AC%E5%88%BA'    print '第'+str(num)+'页','url:'+url   #Determine whether the title contains key   getTitle(url)   time.sleep(2)   num = num + 1  else:   print 'Download Over!!!'   #get the runtime  endtime = datetime.datetime.now()  print 'The Running time : ',(endtime - starttime).seconds    main()

代码解析:

        源程序主要步骤如下:

        1.入口main函数中,在E盘下创建图片文件夹Picture_HP,然后输入图集url,本打算输入tag来进行访问的,因为URL如下:

        http://photo.hupu.com/nba/tag/马刺

        但是解析URL中文总是错误,故改成输入URL,这不影响大局。同时你可能发现了代码中while循环条件为num<=1,它只执行一次,建议需要下载哪页图集,就赋值URL即可。但是虎扑的不同页链接如下,通过分析URL拼接也是可以实现循环获取所有页的。

        http://photo.hupu.com/nba/tag/%E9%99%88%E9%9C%B2?p=2&o=1

       2.调用getTitle(rul)函数,通过Selenium和Phantomjs分析HTML的DOM结构,通过find_elements_by_xpath函数获取原图路径URL、图集的主题和图片数量。如图:

通过该函数即可获取每个图集的主题、URL及图片个数,同时根据图集主题创建相应的文件夹,代码中涉及正则表达式获取图片数量,从"共19张"到数字"19"。如图:

3.再调用函数getScript(elem_url, path, nums),参数分别是图片url、保存路径和图片数量。那么如何获取下一张图片的URL呢?

当通过步骤二爬取了图集URL,如:http://photo.hupu.com/nba/p29556.html

(1).如果是通过Ajax、JavaScript动态加载的图片,url无规律则需要调用Selenium动态模拟鼠标操作点击“下一张”来获取原图url;

(2).但很多网站都会存在一些规律,如虎扑的第九张图片链接如下,通过URL字符串分割处理即可实现:"p29556-"+"数字"+".html"即可。

http://photo.hupu.com/nba/p29556-9.html

在该函数中,我第一次也是通过Selenium分析HTML结构获取原始图片url,但每张图片都需要调用一次Phantomjs无界面浏览器,这速度太慢了。故该成了正则表达式获取HTML中的原图URL,其原因如下图:

虎扑又偷懒了,它在下面定义了原图链接,直接获取即可。

4.最后一步即urllib.urlretrieve(pic_url, pic_path + pic_name)下载图片即可。

当然你可能会遇到错误“Error: [Errno 22] invalid mode ('wb') or filename”,参考 stackoverflow

总结:

这是一篇讲述Selenium和Python爬取虎扑图集的文章,文章内容算是爬虫里面比较基础的,其中下载的“陈露”图片和网站给出的34个图集、902张图片一样。同时采用正则后时间估计3分钟左右,很快~当然,虎扑里面的标签很多,足球应该也是类似,只要修改URL即可下载图集,非常之方便。

以上就是本文关于python爬虫系列Selenium定向爬取虎扑篮球图片详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

Python爬虫实例爬取网站搞笑段子

Python探索之爬取电商售卖信息代码示例

python中requests爬去网页内容出现乱码问题解决方法介绍

如有不足之处,欢迎留言指出。


  • 上一条:
    python机器学习库常用汇总
    下一条:
    给你选择Python语言实现机器学习算法的三大理由
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客