Web測試入門:Selenium+Chrome+Python+Mac OS

1、環境配置

  1. Chromedriver 下載及環境配置
  • url:使用WebDriver在Chrome瀏覽器上進行測試時,須要從http://chromedriver.storage.googleapis.com/index.html網址中下載與本機chrome瀏覽器對應的驅動程序,驅動程序名爲chromedriver;
  • 解壓chromedriver,並將其mv 到/usr/local/bin下(目錄下必需要有對應版本的driver);
  1. 安裝selenium:執行 python -m pip install selenium

2、簡單的 python 程序

  • 示例1:find_element_by_id()方法
# coding = utf-8
from selenium import webdriver
from time import sleep, ctime
import os

driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
driver.find_element_by_id("kw").send_keys("MacOS")
driver.find_element_by_id("su").click()
sleep(5)
driver.quit()
  • 示例2: (ffind_element_by_xpath()方法)
# coding = utf-8
from selenium import webdriver
from time import sleep, ctime
import os

driver = webdriver.Chrome()
driver.get("https://dblp.uni-trier.de/search/")
driver.find_element_by_xpath('//*[@id="completesearch-form"]/input').send_keys(" zhou zhihua")

sleep(5)

driver.find_element_by_xpath('//*[@id="completesearch-authors"]/div/ul/li/a').click()

sleep(15)


driver.quit()

3、 webdriver 的一些用法

  • 定位方法:selenium總共有八種定位方法
  1. By.id() 經過id定位
  2. By.name() 經過name 定位
  3. By.xpath() 經過xpath定位
  4. By.className() 經過className定位
  5. By.cssSelector() 經過CSS 定位
  6. By.linkText() 經過linkText
  7. By.tagName() 經過tagName
  8. By.partialLinkText() 經過匹到的部分linkText
  • Chrome 元素查找
  1. 打開開發者工具
  2. 移動到對應元素上。注意,尋找 Browser中對應的高亮提示(以下圖1),其實是在開發者工具Elements 視圖上移動光標行(圖2)

    圖1 瀏覽器中高亮提示(隨開發者工具 Elements 視圖中光標行的移動)css

  3. 右鍵copy 元素 xpath 或其餘定位參數

    圖2 移動源代碼中光標行(尋找須要定位的元素)html

  4. paste 到腳本中python

相關文章
相關標籤/搜索