Chrome和ChromeDriver版本对应

查看自己Chrome浏览器版本:chrome://version/
image.png
去ChromeDriver网站下载对应版本的驱动

image.png

初始化

  1. from selenium import webdriver
  2. from selenium.webdriver.common.by import By
  3. from selenium.webdriver.support.ui import WebDriverWait
  4. from selenium.webdriver.support import expected_conditions as EC
  5. chromedriver = './chromedriver.exe'
  6. options = webdriver.ChromeOptions()
  7. # chrome_options.add_argument('--disable-gpu')
  8. # chrome_options.add_argument('--headless')
  9. # chrome_options.add_argument('--no-sandbox')
  10. # chrome_options.add_argument('--disable-dev-shm-usage')
  11. # chrome_options.add_argument('window-size=1920x1480')
  12. options.add_argument("start-maximized")
  13. service = webdriver.chrome.service.Service(chromedriver)
  14. browser = webdriver.Chrome(service=service, options=options)

元素选择

find_element_by_*已废弃,用**find_element(by, value)**替代

  • by: By.ID, By.CSS_SELECTOR, By.XPATH, By.CLASS_NAME
  1. browser.find_element_by_css_selector('input[type="text"]')
  2. browser.find_element(By.CSS_SELECTOR, 'input[type="text"]')
  3. browser.find_element('css selector', 'input[type="text"]')

事件触发

  1. # 输入框填写
  2. browser.find_element(By.CSS_SELECTOR, 'input[type="text"]').send_keys('username')
  3. # 清除
  4. browser.find_element(By.CSS_SELECTOR, 'input[type="text"]').clear()
  5. # 点击事件
  6. browser.find_element(By.CSS_SELECTOR, 'input[type="submit"]').click()
  7. # 截屏
  8. browser.save_screenshot('out.png')
  9. # 刷新页面
  10. browser.refresh()
  11. # 关闭当前窗口
  12. browser.close()
  13. # 关闭浏览器和驱动程序
  14. browser.quit()
  15. # 当前网页源码
  16. browser.page_source
  17. # soup = bs4.BeautifulSoup(browser.page_source, 'html.parser')

headless模式

  1. chrome_options.add_argument('--headless')

cookies读写

  1. # dump
  2. cookies = browser.get_cookies()
  3. # json.dump to a file
  4. # load
  5. # json.load cookies from a file
  6. for cookie in cookies:
  7. browser.add_cookie(cookie)

等待

隐式模式

  1. browser.implicitly_wait(30)

显示模式

  1. from selenium.webdriver.support.ui import WebDriverWait
  2. from selenium.webdriver.support import expected_conditions as EC
  3. wait = WebDriverWait(browser, 10)
  4. wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input:nth-child(1)'))).click()
  5. wait.until(EC.element_to_be_selected((By.CSS_SELECTOR, 'ul li:nth-child(3)'))).click()