爬虫某个网站时,如果网站是通过js动态请求后台加载的html页面时,通过传统的scrapy进行爬取时,是获取不到js加载后的内容的。
如何解决爬取这类动态网站呢?且看详情。
工具:scrapy_splash
什么是scrapy_splash?
- scrapy-splash加载js数据是基于Splash来实现的。
- Splash是一个Javascript渲染服务。它是一个实现了HTTP API的轻量级浏览器,Splash是用Python和Lua语言实现的,基于Twisted和QT等模块构建。
- 使用scrapy-splash最终拿到的response相当于是在浏览器全部渲染完成以后的网页源代码。
官方网站:https://splash-cn-doc.readthedocs.io/zh-cn/latest/Installation.html
splash的作用:
scrapy-splash能够模拟浏览器加载js,并返回js运行后的数据
功能
来看看官网的介绍,他能干啥:
- Take screenshots of multiple pages
- Wait for element
- Scroll page
- Preload jQuery
- Preload functions
- Load multiple pages
- Count DIV tags
- Call Later
- Render PNG
- Take a screenshot of a single element
- Log requested URLs
- Block CSS
- Execute function with timeout
- Submit a search input
对于我们普通使用用户来说,加载js,滚动页面,等待js加载,截图应该比较有用。
需要的大家自己去搜索用法吧。
安装
linux + docker
下载 docker
拉取镜像
1 | docker pull scrapinghub/splash |
启动容器
1 | docker run -p 8050:8050 -p 5023:5023 scrapinghub/splash |
现在splash在0.0.0.0这个ip上监听并绑定了端口8050(http) 和5023 (telnet)
启动完splash后,可以访问它的web页面,看是否启动成功:
http://127.0.0.1:8050
scrapy使用splash
安装
1 | pip install scrapy-splash |
新建爬虫项目:
1 | scrapy startproject test_splash |
修改settings.py
1 | # 在settings.py文件中添加splash的配置以及修改robots协议 |
修改爬虫代码
spiders/splash_test.py
1 | # spiders/with_splash.py |
js加载后的html文件内容就保存在with_splash.html文件中了。
如果你想通过scrapy解析加载后的html内容,那直接操作response即可。
1 | def parse_splash(self, response): |
好了,记录到这里。
好记性不如烂笔头。
欢迎关注微信公众号,你的资源可变现:【乐知付加密平台】
一起学习,一起进步。
