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

Table of Contents

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

1.安装selenium

pip install selenium


  * 1

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      # 查看版本


  * 1
  * 2
  * 3
  * 4
  * 5

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



  * 1
  * 2
  * 3
  * 4
  * 5
  * 6
  * 7
  * 8
  * 9
  * 10

解决办法就是把该路径下的chromedriver提权。

chmod 777 chromedriver


  * 1

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()


  * 1
  * 2
  * 3
  * 4
  * 5
  * 6
  * 7
  * 8
  * 9
  * 10
  * 11
  * 12

成功打印出 网页内容 ,那就ok了 !!!!

0 评论

发表评论

精品游戏◆乐于分享


Title