前面几篇文章介绍了Selenium、PhantomJS的基础知识及安装过程,这篇文章是一篇应用。通过Selenium调用Phantomjs获取CSDN下载资源的信息,最重要的是动态获取资源的评论,它是通过JavaScript动态加载的,故通过Phantomjs模拟浏览器加载获取。
        希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~
        [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上)
        [Python爬虫] 在Windows下安装PIP+Phantomjs+Selenium
        [Python爬虫] Selenium自动访问Firefox和Chrome并实现搜索截图
        [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍

源代码

  1. # coding=utf-8
  2.  
  3. from selenium import webdriver
  4. from selenium.webdriver.common.keys import Keys
  5. import selenium.webdriver.support.ui as ui
  6. from selenium.webdriver.common.action_chains import ActionChains
  7. import time
  8. import re
  9. import os
  10.  
  11. #打开Firefox浏览器 设定等待加载时间 访问URL
  12. driver = webdriver.PhantomJS(executable_path="G:\phantomjs-1.9.1-windows\phantomjs.exe")
  13. driver_detail = webdriver.PhantomJS(executable_path="G:\phantomjs-1.9.1-windows\phantomjs.exe")
  14. wait = ui.WebDriverWait(driver,10)
  15. driver.get("http://download.csdn.net/user/eastmount/uploads")
  16. SUMRESOURCES = 0 #全局变量 记录资源总数(尽量避免)
  17.  
  18. #获取列表页数 <div class="page_nav>共46个 共8页..</div> def getPage(): number = 0 wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='page_nav']"))
  19. texts = driver.find_element_by_xpath("//div[@class='page_nav']").text
  20. print texts
  21. m = re.findall(r'(\w*[0-9]+)\w*',texts) #正则表达式寻找数字
  22. print '页数:' + str(m[1])
  23. return int(m[1])
  24.  
  25. #获取URL和文章标题
  26. def getURL_Title(num):
  27. global SUMRESOURCES
  28. url = 'http://download.csdn.net/user/eastmount/uploads/' + str(num)
  29. print unicode('下载列表URL: ' + url,'utf-8')
  30. '''''
  31. ' 等待最下面页面加载成功 获取URL和标题
  32. ' 源码
  33. ' <div class='list-container mb-bg'>
  34. ' <dl>
  35. ' <dt>
  36. ' <div class="icon"><img src="xxx"></img></div>
  37. ' <h3><a href="/detail/eastmount/8757243">MFC显示BMP图片</a></h3>
  38. ' </dt>
  39. ' </dl>
  40. ' </div>
  41. ' get_attribute('href')获取URL且自动补齐
  42. ' unicode防止报错 - s.encode('utf8')unicode转换成utf8编码 decode表示utf8转换成unicode
  43. '''
  44. driver.get(url)
  45. wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='page_nav']"))
  46. list_container = driver.find_elements_by_xpath("//div[@class='list-container mb-bg']/dl/dt/h3/a")
  47. for title in list_container:
  48. print 'Num' + str(SUMRESOURCES +1)
  49. print u'标题: ' + title.text
  50. print u'链接: ' + title.get_attribute('href')
  51. SUMRESOURCES = SUMRESOURCES +1
  52. #
  53. #获取具体内容和评论
  54. getDetails( str(title.get_attribute('href')) )
  55. else:
  56. print ' ' #换行
  57.  
  58. #获取详细信息 因前定义的driver正在使用中 故调用driver_detail
  59. #否则报错 Message: Error Message => 'Element does not exist in cache'
  60. def getDetails(url):
  61. #获取infobox
  62. driver_detail.get(url)
  63. details = driver_detail.find_element_by_xpath("//div[@class='info']").text
  64. print details
  65. #加载评论 <dl><dt></dt><dd></dd></dl>
  66. comments = driver_detail.find_elements_by_xpath("//dl[@class='recom_list']/dd")
  67. for com in comments:
  68. print u'评论:' + com.text
  69. else:
  70. print ' ' #换行
  71.  
  72. #主函数
  73. def main():
  74. start = time.clock()
  75. pageNum = getPage()
  76. i=1
  77. #循环获取标题和URL
  78. while(i<=pageNum):
  79. getURL_Title(i)
  80. i = i + 1
  81. else:
  82. print 'SUmResouces: ' + str(SUMRESOURCES)
  83. print 'Load Over'
  84. end = time.clock()
  85. print "Time: %f s" % (end - start)
  86.  
  87. main()

代码实现步骤

1.首先获取页面总数,通过getPage()函数实现;
        2.每个页面有一列资源,通过driver的find_element_by_xpath()路径获取标题和get_attribute('href')函数获取URL,它会自动补齐链接;
        3.根据步骤2获取资源的URL,去到具体资源获取消息框和评论信息;
        4.由于采用Phantomjs无界面浏览器加载页面,故获取class=info和recom_list的div即可。

运行结果

运行结果如下图所示:

程序分析

首先获取如下图所示的页面总数,此时为“8”页。它通过如下代码实现:
        texts = driver.find_element_by_xpath("//div[@class='page_nav']").text
        然后再while(i<=8)依次遍历每页的资源,每页资源的URL链接为:
        http://download.csdn.net/user/eastmount/uploads/8

再获取每页所有资源的标题及URL,通过代码如下:

  1. list_container = driver.find_elements_by_xpath("//div[@class='list-container mb-bg']/dl/dt/h3/a")
  2. for title in list_container:
  3. print 'Num' + str(SUMRESOURCES +1)
  4. print u'标题: ' + title.text
  5. print u'链接: ' + title.get_attribute('href')

其中对应的源码如下所示,通过获取find_elements_by_xpath()获取多个元素,其div的class='list-container mb-bg',同时路径为<div><dl><dt><h3><a>即可。同时自动补齐URL,如:
        <a href='/detail/eastmount/6917799'会添加“http://download.csdn.net/”。

最后在进入具体的资源获取相应的消息盒InfoBox和评论信息,由于通过模拟Phantomjs浏览器直接可以显示动态JS评论信息。

而如果通过BeautifulSoup只能获取的HTML源码如下,并没有JS信息。因为它是动态加载的,这就体现了Phantomjs的优势。而通过Chrome或FireFox浏览器审查元素能查看具体的评论div,这也是模拟浏览器的用处所在吧!
        可对比前面写过的文章:[Python学习] 简单爬取CSDN下载资源信息

  1. <div class="section-list panel panel-default">
  2. <div class="panel-heading">
  3. <h3 class="panel-title">资源评论</h3>
  4. </div>
  5. <!-- recommand -->
  6. <script language='JavaScript' defer type='text/javascript' src='/js/comment.js'></script>
  7. <div class="recommand download_comment panel-body" sourceid="8772951"></div>
  8. </div>

总结

这篇文章主要讲述通过Selenium和Phantomjs获取CSDN下载资源信息的过程,其中由于driver调用Chrome或FireFox浏览器总会有额外空间增加,故调用Phantomjs无界面浏览器完成。同时有几个问题:
            1.如何避免Phantomjs的黑框弹出;
            2.程序的运行时间比较低,响应时间较慢,如何提高?
        接下来如果有机会准备尝试的内容包括:
            1.下载百度百科的旅游地点InfoBox(毕设知识图谱挖掘);
            2.如何爬取搜狐图片的动态加载图片,完成智能爬图工具;
            3.当需要自动登录时driver访问Chrome或FireFox浏览器发送消息。
        最后希望文章对你有所帮助吧!如果有错误或不足之处,还请海涵~
      (By:Eastmount 2015-8-24 深夜2点半   http://blog.csdn.net/eastmount/

[Python爬虫] Selenium+Phantomjs动态获取CSDN下载资源信息和评论的更多相关文章

  1. [Python爬虫] 之一 : Selenium+Phantomjs动态获取网站数据信息

    本人刚才开始学习爬虫,从网上查询资料,写了一个利用Selenium+Phantomjs动态获取网站数据信息的例子,当然首先要安装Selenium+Phantomjs,具体的看 http://www.c ...

  2. [Python爬虫] Selenium爬取新浪微博客户端用户信息、热点话题及评论 (上)

    转载自:http://blog.csdn.net/eastmount/article/details/51231852 一. 文章介绍 源码下载地址:http://download.csdn.net/ ...

  3. [Python爬虫] Selenium +phantomjs 模拟下拉滚动条

    在爬虫中,有时会遇到这种情况,数据的展示是不是一页一页的,而是通过不断的下拉滚动条来加载数据.例如一点咨询(http://www.yidianzixun.com/)和微博(在未登录的状态下:http: ...

  4. [python爬虫] Selenium常见元素定位方法和操作的学习介绍

    这篇文章主要Selenium+Python自动测试或爬虫中的常见定位方法.鼠标操作.键盘操作介绍,希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~同时CSDN总是屏蔽这篇文章,再加上最近 ...

  5. [Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒

    前面我讲述过如何通过BeautifulSoup获取维基百科的消息盒,同样可以通过Spider获取网站内容,最近学习了Selenium+Phantomjs后,准备利用它们获取百度百科的旅游景点消息盒(I ...

  6. [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍

    前三篇文章介绍了安装过程和通过Selenium实现访问Firefox浏览器并自动搜索"Eastmount"关键字及截图的功能.而这篇文章主要简单介绍如何实现自动登录163邮箱,同时 ...

  7. Python 爬虫修养-处理动态网页

    Python 爬虫修养-处理动态网页 本文转自:i春秋社区 0x01 前言 在进行爬虫开发的过程中,我们会遇到很多的棘手的问题,当然对于普通的问题比如 UA 等修改的问题,我们并不在讨论范围,既然要将 ...

  8. python爬虫---selenium库的用法

    python爬虫---selenium库的用法 selenium是一个自动化测试工具,支持Firefox,Chrome等众多浏览器 在爬虫中的应用主要是用来解决JS渲染的问题. 1.使用前需要安装这个 ...

  9. Python爬虫-selenium的使用(2)

    使用selenium打开chrome浏览器百度进行搜索 12345678910111213141516171819202122232425 from selenium import webdriver ...

随机推荐

  1. afterTextChanged() callback being called without the text being actually changed

    afterTextChanged() callback being called without the text being actually changed up vote8down votefa ...

  2. 问题: ActivityManager: Warning: Activity not started, its current task has been brought to the front

    运行程序时看控制台有这样的错误,应用程序没跑起来. 解决办法:project-->Clean

  3. mysql事务处理用法与实例详解

    来源:转载  MySQL的事务支持不是绑定在MySQL服务器本身,而是与存储引擎相关1.MyISAM:不支持事务,用于只读程序提高性能 2.InnoDB:支持ACID事务.行级锁.并发 3.Berke ...

  4. zoj1260 king

    题目描述:从前有一个王国,皇后怀孕了.她祈祷到:如果我的孩子是儿子,我希望他是一个健康的国王. 9 个月后,她的孩子出生了,的确,她生了一个漂亮的儿子.但不幸的是,正如皇室家庭经常发生的那样,皇后的儿 ...

  5. openssl API网络通信

    1.本文是在别人的基础上,经过测试,大体总结的.操作环境ubuntu12和ubuntu14 ****************************************************** ...

  6. python之优雅处理套接字错误

    #!/usr/local/bin/python3.5 #coding:utf-8 import sys import socket import argparse def main(): #setup ...

  7. [转] mhvtl虚拟磁带库的安装与应用

    转自:candon123  -- http://candon123.blog.51cto.com/704299/388192/ 1.获取mhvtl: 官方网站:http://mhvtl.nimsa.u ...

  8. VS2010安装异常中断后无法安装的解决方法(安装时发生严重错误)

    最近,因为公司开发的需要,对开发环境进行全面的升级,在这其中也遇到了不少问题,在之后将陆续整理出来,以便以后查看. 之前开发环境:ArcGIS9.3,ArcEngine9.3,Oracle10g,Ar ...

  9. makeinfo: command not found

    解决办法:sudo apt-get install texinfo

  10. I hate it

    Description 很多学校流行一种比较的习惯.老师们很喜欢询问,从某某到某某当中,分数最高的是多少.这让很多学生很反感. 不管你喜不喜欢,现在需要你做的是,就是按照老师的要求,写一个程序,模拟老 ...