Scrapy爬虫中使用Splash处理页面JS
来源:互联网 发布:淘宝宝贝搜索不到 编辑:程序博客网 时间:2024/05/21 08:55
http://ae.yyuap.com/pages/viewpage.action?pageId=919763
摘要:
- Splash简介
- Splash安装
- Splash与Scrapy结合
- 使用Splash执行Javascript
- 参考资料
使用Javascript渲染和处理网页是种非常常见的做法,如何处理一个大量使用Javascript的页面是Scrapy爬虫开发中一个常见的问题,这篇文章将说明如何在Scrapy爬虫中使用Splash来处理页面中得Javascript。
Splash简介
Splash是一个Javascript渲染服务。它是一个实现了HTTP API的轻量级浏览器,Splash是用Python实现的,同时使用Twisted和QT。Twisted(QT)用来让服务具有异步处理能力,以发挥webkit的并发能力。
Splash安装
安装Splash最简单的方式是使用Docker,只需要执行下面命令
$ docker pull scrapinghub/splash
$ docker run -p 8050:8050 scrapinghub/splash
Splash与Scrapy结合
Scrapy爬虫中如何使用Splash服务?使用ScrapyJS是官方推荐的方式。
1.安装ScrapyJS:
pip install scrapyjs
2.修改Scrapy项目配置
在Scrapy项目的settings.py中添加下面代码:
3.请求中添加Splash参数
在Scrapy请求的meta中使用splash参数,则该请求会发送的Splash服务进行渲染
如果需要从起始url就进行渲染,则需要修改start_requests方法
请求中具体的参数参考http://splash.readthedocs.org/en/latest/api.html
使用Splash执行Javascript
Splash官方推荐使用Splash Scripts(Lua脚本)执行Javascript,示例如下:
示例中script为一个Splash Scripts,该脚本跳转到http://example.com,等待0.5秒,执行一个Javascript(document.title),返回{title=Javascript执行结果}的一个lua table;
parse方法中将获得一个JSON返回值
{
"title": "Some title"
}
每个Splash Scripts都需要一个main方法作为入口。返回值中Lua table将会转为JSON
很多场景下都需要页面点击一个按钮,然后获取页面中的一部分数据;可以使用JQuery点击实践来实现,Splash Script示例如下:
function main(splash)
splash:autoload("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js")
splash:go("http://example.com")
splash:runjs("$('#some-button').click()")
return splash:html()
end
参考资料
Scrapinghub博客:http://blog.scrapinghub.com/
Splash官方文档:http://splash.readthedocs.org/en/latest/scripting-tutorial.html
Github中ScrapyJS项目:https://github.com/scrapinghub/scrapyjs
- Scrapy爬虫中使用Splash处理页面JS
- Scrapy爬虫中使用Splash抓取动态JS页面
- 利用scrapy-splash爬取JS生成的动态页面
- scrapy-splash爬取JS生成的动态页面
- Splash动态页面爬虫
- scrapy-splash 爬虫渲染异步加载,ajax
- scrapy-redis集成scrapy-splash使用教程
- Scrapy+splash抓取js生成的数据
- splash爬虫
- python3 网络爬虫(五)scrapy中使用User-Agent
- 使用scrapy编写的爬虫
- 使用Docker部署Scrapy爬虫
- 使用Scrapy框架编写爬虫
- scrapy爬虫框架的使用
- 使用Scrapy框架编写爬虫
- 使用scrapy编写爬虫入门
- 第1.8章 scrapy之splash的使用
- 分布式下的爬虫Scrapy应该如何做-关于动态内容js或者ajax处理(2)
- Xcode插件管理工具Alcatraz
- 千万别在最能吃苦的年纪选择安逸
- OFBiz系统环境搭建
- 调用回调方法有返回值的情况
- 收缩导航条
- Scrapy爬虫中使用Splash处理页面JS
- 6、抽象类与接口
- SDWebImage源码分析
- onCreate()方法中获取View的宽高为0的原因及解决方法
- Android Handler
- CentOS、Rhel永久修改hostname
- 数据结构实验之链表七:单链表中重复元素的删除
- [前端]
- Android 编写文件浏览器