上古有大椿者,以八千岁为春,八千岁为秋。网站首页详情 阿里云Ubuntu服务器 使用selenium chrome + headless(无头-无界面) 阿里云使用ubuntu服务器上使用selenium自动化爬虫,需要安装好谷歌浏览器(也可以是其他的浏览器)和对应版本的驱动,以及selenium需要配置好headless,no-sandbox等。 ## 1.安装selenium ```python pip install selenium ``` ## 2.安装谷歌浏览器 ```python sudo apt-get install libxss1 libappindicator1 libindicator7 wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb sudo dpkg -i google-chrome*.deb # Might show "errors", fixed by next line sudo apt-get install -f#安装依赖 google-chrome --version # 查看版本 ``` ## 3.安装 chromdriver 进入[阿里云镜像](https://npm.taobao.org/)下载chromdriver  下载与上面对应的谷歌浏览器对应的chromdriver。一般是下载最新的。 可以查看 notes.txt 文件,看chrome 和ChromDriver 两者相对应的兼容版本  下载 chromedriver_linux64.zip 解压 得到 chromedriver文件 远程 把chromedirver 文件放到线上服务器 目录/usr/bin/ 下。 如果报权限不够的错误 ```python During handling of the above exception, another exception occurred: Traceback (most recent call last): File “amac_project_msg.py”, line 7, in <module> browser = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver", chrome_options=opt) File “/root/anaconda3/envs/opinion/lib/python3.5/site-packages/selenium/webdriver/chrome/webdriver.py”, line 73, in init self.service.start() File “/root/anaconda3/envs/opinion/lib/python3.5/site-packages/selenium/webdriver/common/service.py”, line 88, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: ‘chromedriver’ executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home ``` 解决办法就是把该路径下的chromedriver提权。 ```python chmod 777 chromedriver ``` ## 4.测试 ```python from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless')#无头模式,服务器没有图形界面这个必须 chrome_options.add_argument('--disable-gpu')#不需要gpu加速 chrome_options.add_argument('--no-sandbox') # 这个配置很重要 client = webdriver.Chrome(chrome_options=chrome_options, executable_path='/home/chromedriver') # 如果没有把chromedriver加入到PATH中,就需要指明路径 client.get("https://www.baidu.com") print (client.page_source.encode('utf-8')) client.quit() ``` 成功打印出 网页内容 ,那就ok了 !!!! 很赞哦! ( 666) 打赏本站 关闭 感谢您的支持,我会继续努力的! 扫码打赏,你说多少就多少 相关文章 设计中 文章评论 文章写的很棒,继续加油! 关注我们 么么哒! 小程序名Gary自学 QQ号1349380978 特别推荐 我的blog发展历程 阅读 留言告诉我你的声音 阅读 个人博客,属于我的小世界! 阅读