phantomjs 可贵的是无头 Webkit 不需要系统提供任何 X display 支持,适合部署到服务器。缺点自然是无法支持 flash 等插件。
上次试了试 ghostdriver 感觉程序不是很成熟,填写字段时常有失灵的时候。于是又打起来 phantomjs 的主意。网上查到 PyPhantomJS ,但已经停止开发,可惜。
不过自0.1.8 开始 phantom 加入了webdriver支持,最新的selenium中也加入了phantom 。现在 python 通过 webdriver 驱动 phantomjs 变得异常简单。试了试 Webdriver 的 python binding, 感觉 API 用起来比较啰嗦,太长,用不惯。github 上看到了 selenium wrapper 。用起来可以少敲不少字符:
打开命令行窗口:
下载 phatomjs 的 windows 版,
E:\Python27\scripts>pip install seleniumwrapper
E:\phantomjs-1.8.0-windows>start phantomjs.exe --webdriver=3300 --proxy-type=none //proxy none 不设置会引起window下浏览慢
PhantomJS is launching GhostDriver...
Ghost Driver running on port 3300
E:\phantomjs-1.8.0-windows>python
>> import seleniumwrapper as slwrp
>> br = slwrp.connect('PhatomJS','http://localhost:3300')
>> br.get('http://baidu.com')
>> br.by_id('kw').sendkeys('baidu search sucks')
>> print br.by_id('content_left').text.encode('gbk','ignore')
.................................
.................................
>> br.get_screenshot_as_file('e://test.jpg')
True
>>^Z
Selenium的doc信息很完整,对于向我一样的Selenium新手,也许你会发现 pydoc 有用:
pythonw.exe E:\Pyton27\Tools\scripts\pydocgui.pyw
http://localhost:7464/selenium.webdriver.phantomjs.webdriver.html
http://localhost:7464/selenium.webdriver.remote.webelement.html
http://localhost:7464/seleniumwrapper.wrapper.html
不幸的是 phantomjs 在我的 Linux 测试中不能用,总是卡在 br.get(url) 这里不动。netstat 观察,phantomjs根本没有发出任何localhost以外的连接。不知怎么办?