爬虫之Splash API调用(上)
一 点睛
如何才能利用Splash渲染页面呢?怎样才能和Python程序结合使用并抓取JavaScript渲染的页面呢?
其实Splash给我们提供了一些HTTP API接口,我们只需要请求这些接口并传递相应的参数即可。
二 render.html
1 点睛
此接口用于获取JavaScript渲染的页面的HTML代码,接口地址就是Splash的运行地址加此接口名称。
例如http://localhost:8050/render.html。
我们给此接口传递了一个url参数来指定渲染的URL,返回结果即页面渲染后的源代码。
2 代码
import requests
url = 'http://localhost:8050/render.html?url=https://www.baidu.com'
response = requests.get(url)
print(response.text)
3 结果
4 说明
这样就可以成功输出百度页面渲染后的源代码了。
5 实战
5.1 点睛
此接口还可以指定其他参数,比如通过wait指定等待秒数。如果要确保页面完全加载出来,可以增加等待时间。
5.2 代码
import requests
url = 'http://localhost:8050/render.html?url=https://www.taobao.com&wait=5'
response = requests.get(url)
print(response.text)
5.3 结果
5.4 说明此时得到响应的时间就会相应变长,比如这里会等待5秒多钟才能获取淘宝页面的源代码。
另外,此接口还支持代理设置、图片加载设置、Headers设置、请求方法设置,具体的用法可以参见官方文档https://splash.readthedocs.io/en/stable/api.html#render-html。
三 render.png
1 点睛
此接口可以获取网页截图,其参数比render.html多了几个,比如通过width和height来控制宽高,它返回的是PNG格式的图片二进制数据。
2 代码
import requests
url = 'http://localhost:8050/render.png?url=https://www.jd.com&wait=5&width=1000&height=700'
response = requests.get(url)
with open('taobao.png', 'wb') as f:
f.write(response.content)
3 效果
产生图片
4 说明
这样我们就成功获取了京东首页渲染完成后的页面截图,详细的参数设置可以参考官网文档https://splash.readthedocs.io/en/stable/api.html#render-png。
四 render.jpeg
此接口和render.png类似,不过它返回的是JPEG格式的图片二进制数据。
另外,此接口比render.png多了参数quality,它用来设置图片质量。
五 render.har
1 点睛
此接口用于获取页面加载的HAR数据
2 代码
curl http://localhost:8050/render.har?url=https://www.jd.com&wait=5
3 说明
它的返回结果非常多,是一个JSON格式的数据,其中包含页面加载过程中的HAR数据。