原理讲解:python中 selenium 调用webdriver 启动浏览器爬取数据,最为简单的是webdriver直接驱动chrome无界面模式。但是想要浏览器稳定些,可以在页面长期挂着一个浏览器,然后driver 通过端口连接,进而获取数据,接下来通过chrome浏览器,chromedriver进行实战。

#安装好chrome 以及对应版本的chromedriver

1、页面启动chrome 并且指定端口13888(任意未占用的端口)

(windows )

chrome.exe --remote-debugging-port=13888

(linux)

chrome --no-sandbox --remote-debugging-port=13888  --user-data-dir=/data/chrome/13888 --ignore-certificate-errors

2、selenium chromedriver 连接 两种方法

(1)chromedriver 连接 监听始终端口13888的chrome 浏览器

#chromedriver 连接 监听始终端口13888的chrome 浏览器
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument('--remote-debugging-port=13888')
driver = webdriver.Chrome(options=chromeOptions)

(2)chromedriver 连接 已经启动的chrome 端口为13888的chrome 浏览器

#chromedriver 连接 已经启动的chrome 端口为13888的chrome 浏览器
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:13888")
driver = webdriver.Chrome(options = chrome_options)

3、数据获取 (正常webdriver的操作)

driver.get('https://www.baidu.com')

4、远程webdriver

根据不同的业务场景,有些业务需要使用到远程webdriver,在启用chrome浏览器的机子上,启用远程webdriver

./chromedriver --port=13889 --whitelisted-ips --enable-webgl --no-sandbox --disable-dev-shm-usage --disable-gpu --allowed-origins="*"

--allowed-origins="*"指定所有ip可以访问

--no-sandbox 一般是linux系统中会用到

--disable-gpu 指定不是用gpu加速

5、连接远程webdriver

chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument('--remote-debugging-port=13888')
driver = webdriver.Remote(command_executor='http://ip:13889',options=chromeOptions)

连接后 就可以经行正常的driver请求和操作了。

GitHub 加速计划 / li / linux-dash
7
1
下载
A beautiful web dashboard for Linux
最近提交(Master分支:6 个月前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐