python chrome 爬虫

2017-11-17  本文已影响0人  jojo1313

参考:
http://www.siyuweb.com/auottest/3057.html
http://fex.baidu.com/blog/2014/06/remote-debugging-protocol/

环境:python 3.5+

意图:
利用remote debugging protocol(远程调试协议)爬取目标站点所有链接

远程调试协议基于 WebSocket,利用 WebSocket 建立连接 DevTools 和浏览器内核的快速数据通道.

页面爬取流程:
下载启动chrmoe server
-->get webSocketDebuggerUrl
--> page.navigate(url#目标站点)
--> {Network.requestWillBeSent 获取事件['request']['url'],
DOM.getDocument获取页面数据--> DOM.getOuterHTML解析dom }
-->事件中获取的url+dom解析的总数等于最终获取的url

下载chrome server:

yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum install mesa-libOSMesa-devel gnu-free-sans-fonts
ln -s /usr/lib64/libOSMesa.so.8 /opt/google/chrome/libosmesa.so

启动chrome server:

google-chrome --headless --disable-gpu --no-sandbox --blink-settings=imagesEnabled=false --remote-debugging-address='0.0.0.0' --remote-debugging-port=9222

远程调试协议实战:

#get webSocketDebuggerUrl
import json
import requests
def main():
    ws = requests.get("http://127.0.0.1:9222/json/new") #建立一个浏览器tab, xxx/json获取所有已打开tab:
    print (ws.json())
if __name__=='__main__':
    main()

#response
{'id': '2366fc9b-5b69-47ff-bc1d-67c3815c1419', 'webSocketDebuggerUrl': 'ws://127.0.0.1:9222/devtools/page/2366fc9b-5b69-47ff-bc1d-67c3815c1419', 'description': '', 'type': 'page', 'devtoolsFrontendUrl': '/devtools/inspector.html?ws=127.0.0.1:9222/devtools/page/2366fc9b-5b69-47ff-bc1d-67c3815c1419', 'url': 'about:blank', 'title': ''}
上一篇 下一篇

猜你喜欢

热点阅读