参考资料
Selenium的生态
绘图工具:plantuml
Selenium Client:各个语言的封装库
Selenium Server 是一个Remote Webdriver的中转服务
Selenium WebDriver
- self.driver=webdriver.Chrome()
- self.driver=webdriver.Firefox()
- 启动了chromedriver或者geckoDriver
- 调用RemoteWebDriver
Selenium Remote WebDriver
封装了发送http请求到各个驱动的逻辑
selenium IDE
- https://www.seleniumhq.org/selenium-ide/
- Katalon Recorder Chrome扩展
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class Hogwarts(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.katalon.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_hogwarts(self):
driver = self.driver
driver.get("https://testing-studio.com/")
driver.find_element_by_link_text(u"学院首页").click()
driver.find_element_by_link_text(u"技术服务").click()
driver.find_element_by_link_text(u"近期内推职位").click()
driver.find_element_by_link_text(u"关于我们").click()
driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='https://testerhome.com/'])[1]/following::p[2]").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
Java示例
package com.example.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Hogwarts {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.katalon.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testHogwarts() throws Exception {
driver.get("https://testing-studio.com/");
driver.findElement(By.linkText("学院首页")).click();
driver.findElement(By.linkText("技术服务")).click();
driver.findElement(By.linkText("近期内推职位")).click();
driver.findElement(By.linkText("关于我们")).click();
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='https://testerhome.com/'])[1]/following::p[2]")).click();
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
FireFox的自动化
常见错误
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
# vi ~/.bash_profile
export PATH=$PATH:/Users/seveniruby/temp/selenium
定位
- id
- name
- css定位 https://www.w3schools.com/cssref/css_selectors.asp
- xpath定位
css定位
- .form-control
- *[name=q]
演示代码
from time import sleep
from unittest import TestCase
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
class TestTesterHome(TestCase):
def test_index(self):
self.driver=webdriver.Firefox()
self.driver.get("https://testerhome.com")
print(self.driver.page_source)
def test_chrome(self):
self.driver=webdriver.Chrome()
self.driver.get("https://testerhome.com")
self.driver.maximize_window()
print(self.driver.page_source)
#self.driver.find_element(By.XPATH, "//*[@placeholder='搜索本站内容']")
self.driver.find_element(By.NAME, "q").send_keys("hogwarts", Keys.ENTER)
#self.driver.find_element(By.XPATH, '//*[@id="main-page"]/div[1]/nav/div/ul[2]/li[1]/form/div/input')
#self.driver.find_element(By.CSS_SELECTOR, "#main-page > div.header > nav > div > ul:nth-child(4) > li.nav-search.hidden-xs.hidden-sm.hidden-md > form > div > input")
def test_windows(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(6)
self.driver.get("https://testerhome.com")
self.driver.maximize_window()
self.driver.find_element(By.PARTIAL_LINK_TEXT, "测试工程师生存指南").click()
self.driver.find_element(By.PARTIAL_LINK_TEXT, "https://jinshuju.net/f/iBwLDt").click()
windows=self.driver.window_handles
self.driver.switch_to.window(windows[1])
print(self.driver.page_source)