selenium+chromedriver在服务器运行的详细教程
1.前言
想使用selenium从网站上抓数据,但有时候使用phantomjs会出错。chrome现在也有无界面运行模式了,以后就可以不用phantomjs了。
但在服务器安装chrome时出现了一些错误,这里总结一下整个安装过程
2.ubuntu上安装chrome
#InstallGoogleChrome #https://askubuntu.com/questions/79280/how-to-install-chrome-browser-properly-via-command-line sudoapt-getinstalllibxss1libappindicator1libindicator7 wgethttps://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb sudodpkg-igoogle-chrome*.deb#Mightshow"errors",fixedbynextline sudoapt-getinstall-f
这时应该已经安装好了,用下边的命行运行测试一下:
google-chrome--headless--remote-debugging-port=9222https://chromium.org--disable-gpu
这里是使用headless模式进行远程调试,ubuntu上大多没有gpu,所以–disable-gpu以免报错。
之后可以再打开一个ssh连接到服务器,使用命令行访问服务器的本地的9222端口:
curlhttp://localhost:9222
如果安装好了,会看到调试信息。但我这里会报一个错误,下边是错误的解决办法。
1)可能的错误解决方法
运行完上边的命令可能会报一个不能在root下运行chrome的错误。这个时候使用下边方设置一下chrome
1.找到google-chrome文件
我的位置位于/opt/google/chrome/
2.用vi打开google-chrome文件
vi/opt/google/chrome/google-chrome
在文件中找到
exec-a"$0""$HERE/chrome""$@"
3.在后面添加–user-data-dir–no-sandbox即可,整条shell命令就是
exec-a"$0""$HERE/chrome""$@"--user-data-dir--no-sandbox
4.再重新打开google-chrome即可正常访问!
3.安装chrome驱动chromedriver
下载chromedriver
chromedriver提供了操作chrome的api,是selenium控制chrome的桥梁。
chromedriver最好安装最新版的,记的我一开始安装的不是最新版的,会报一个错。用最新版的chromedriver就没有问题,最新版的可以在下边地址找到
https://sites.google.com/a/chromium.org/chromedriver/downloads
我写这个文章时最新版是2.37
wgethttps://chromedriver.storage.googleapis.com/2.37/chromedriver_linux64.zip
unzipchromedriver_linux64.zip
到这里服务器端的无界面版chrome就安装好了。
4.无界面版chrome使用方法
fromseleniumimportwebdriver chrome_options=webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument("user-agent='Mozilla/5.0(X11;Linuxx86_64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/62.0.3202.94Safari/537.36'") wd=webdriver.Chrome(chrome_options=chrome_options,executable_path='/home/chrome/chromedriver') wd.get("https://www.163.com") content=wd.page_source.encode('utf-8') printcontent wd.quit()
这里chrome_options中的第三项设置参数,使用这个设置可以避免网站检测到你使用的是无界模式进行反抓取。
下边另外的两项设置,不进行设置时在桌面版linux系统,或者mac系统上会打开有界面的chrome.调试时可以注释掉下边两行使用有界面版chrome来调试程序。
chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu')
5.参考
https://jiayi.space/post/zai-ubuntufu-wu-qi-shang-shi-yong-chrome-headless
https://blog.csdn.net/u013703963/article/details/71083802
总结
到此这篇关于selenium+chromedriver在服务器运行的文章就介绍到这了,更多相关selenium+chromedriver在服务器运行内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!