阿里云Ubuntu服务器 使用selenium chrome + headless(无头-无界面)

阿里云使用ubuntu服务器上使用selenium自动化爬虫,需要安装好谷歌浏览器(也可以是其他的浏览器)和对应版本的驱动,以及selenium需要配置好headless,no-sandbox等。

1.安装selenium

pip install selenium

2.安装谷歌浏览器

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

进入阿里云镜像下载chromdriver
镜像源图片
下载与上面对应的谷歌浏览器对应的chromdriver。一般是下载最新的。
可以查看 notes.txt 文件,看chrome 和ChromDriver 两者相对应的兼容版本
谷歌浏览器
下载 chromedriver_linux64.zip

解压 得到 chromedriver文件

远程 把chromedirver 文件放到线上服务器 目录/usr/bin/ 下。
如果报权限不够的错误

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提权。

chmod 777 chromedriver

4.测试

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了 !!!!

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值