登录root用户,使用pip3安装selenium
[visitor@localhost ~]$ su
Password:
[root@localhost visitor]# pip3 install selenium
Collecting selenium
Downloading selenium-3.11.0-py2.py3-none-any.whl (943kB)
100% |████████████████████████████████| 952kB 41kB/s
Installing collected packages: selenium
Successfully installed selenium-3.11.0
[root@localhost visitor]# exit
exit
安装chrome浏览器和对应的chromedriver
[visitor@localhost ~]$ vim shell_install/google-chrome.repo
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
[visitor@localhost ~]$ sudo cp ~/shell_install/google-chrome.repo /etc/yum.repos.d/
[visitor@localhost ~]$ sudo yum -y install google-chrome-stable –nogpgcheck
[visitor@localhost ~]$ google-chrome -version
Google Chrome 65.0.3325.181
[visitor@localhost ~]$ wget http://npm.taobao.org/mirrors/chromedriver/2.36/chromedriver_linux64.zip
[visitor@localhost ~]$ sudo unzip -d /usr/local/bin chromedriver_linux64.zip
测试例子
[visitor@localhost ~]$ vim openpage.py
# -*- coding: utf-8 -*-
import time
from selenium import webdriver
# chrome采用无界面浏览方式
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=chrome_options)
# chrome采用有界面浏览方式
# driver = webdriver.Chrome() # 使用Chrome浏览器
driver.get('https://www.baidu.com/') # 发送get请求
time.sleep(1) # 休息1s
driver.execute_script('window.open()') # 先打开新的选项卡
print(driver.window_handles)
driver.switch_to_window(driver.window_handles[1]) # 切换选项卡
driver.get('https://www.google.com.hk/') # 发送get请求
print(driver.page_source) # 打印网页内容
driver.close() # 关闭当前标签页
driver.quit() # 关闭浏览器
[visitor@localhost ~]$ python3 openpage.py