1、selenium安装
- 浏览器下载selenium
chrome下载网址:https://chromedriver.storage.googleapis.com/index.html
注:需要下载和chrome浏览器版本和操作系统匹配的驱动 - python下载selenium
pip install selenium -i https://pypi.douban.com/simple
2、selenium基本使用
- 创建谷歌浏览器操作对象
service = Service("chromedriver.exe")
browser = webdriver.Chrome(service=service)
- 访问网址
url = 'https://www.baidu.com'
browser.get(url)
3、元素定位和元素信息
元素定位
格式:browser.find_element(By.XXX,‘xxx’)
应用实例:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
service = Service("chromedriver.exe")
browser = webdriver.Chrome(service=service)
url = 'https://www.baidu.com'
browser.get(url)
# 元素定位
# button = browser.find_element(By.XPATH,'//input[@id="su"]')
button = browser.find_element(By.ID,'su')
print(button)
# 获取元素的标签
print(button.get_attribute('class'))
# 获取标签的名字
print(button.tag_name)
# 省略......
4、交互
应用实例
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
# 创建浏览器对象
service = Service('chromedriver.exe')
browser = webdriver.Chrome(service=service)
# 访问的url
url = 'https://www.baidu.com'
browser.get(url)
time.sleep(2)
# 获取输入框对象
input = browser.find_element(By.ID,'kw')
# 在输入框中输入 邓紫棋
input.send_keys('邓紫棋')
time.sleep(2)
# 获取百度一下的按钮
button = browser.find_element(By.ID,'su')
# 点击百度一下按钮
button.click()
time.sleep(2)
# 滑到浏览器底部
js_bottom = 'document.documentElement.scrollTop=100000'
browser.execute_script(js_bottom)
time.sleep(2)
# 获取下一页按钮
next = browser.find_element(By.XPATH,'//a[@class="n"]')
# 点击下一页
next.click()
time.sleep(2)
# 回到上一页
browser.back()
time.sleep(2)
# 回去
browser.forward()
time.sleep(3)
# 退出浏览器
browser.quit()
5、无界面浏览器(chrome handless)
应用实例:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def share_browser():
# 初始化
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
path = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
chrome_options.binary_location = path
browser = webdriver.Chrome(chrome_options=chrome_options)
# 以上代码都是写死的,只需要改 path为自己浏览器位置
return browser
url = 'https://www.baidu.com'
browser = share_browser()
browser.get(url)
# 拍照片,看是否访问了目标网址
browser.save_screenshot('baidu.png')