selenium+phantomJS爬虫,适用于登陆限制强,点触验证码等一些场景

selenium是非常出名的自己主动化測试工具,多数场景是測试project师用来做自己主动化測试,可是相同selenium能够作为基本上模拟浏览器的工具,去爬取一些基于http request不能或者非常复杂的才干爬取的站点。并且交互式脚本(如:python) + selenium能够直接看到浏览器的运行过程,利于debug,同一时候看上去比較有成就感。

贴个实例吧

firefoxProfile = FirefoxProfile()
# Disable images
firefoxProfile.set_preference('permissions.default.image', 2)
#Disable Flash
firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so','false')

#firefox, chrome, phantomjs
driver = webdriver.Firefox(firefoxProfile)
#login
driver.get("https://www.facebook.com/")
inputEmail = driver.find_element_by_id("email")
inputEmail.send_keys("useruseruseruser")
inputPass = driver.find_element_by_id("pass")
inputPass.send_keys("pwpwpwpwpw")
inputPass.submit()

driver.get("https://www.facebook.com/blablabla" % (page))
driver.execute_script("alert('execute js')")

driver.quit()

配合pyvirtualdisplay能够在后台运行。博友可自行查找其使用方法

相同selenium做爬虫的缺点也是非常明显的:

  1. 慢。异乎平常的慢(单个请求,载入的东西实在是太多了,对多线程也是极不友好的);
  2. 非常吃电脑资源(CPU,网络,内存都是一个非常大的挑战);
  3. 爬取规模不能太大
  4. 。。。。

所以,适用于那些难搞定的小站点。须要登陆的,点触式验证码啊等等

原文地址:https://www.cnblogs.com/jhcelue/p/7347266.html