Selenium和PhantomJS

2021-01-29  本文已影响0人  李霖弢

Selenium是目前使用最广泛的浏览器自动化测试工具,支持不同平台/不同浏览器。可以配合JS测试框架Mocha进行测试。
Selenium自身不带浏览器,需配合浏览器driver实现功能(如Chrome、PhantomJS)

Python

from selenium.webdriver import Chrome
driver = Chrome()
driver.get("https://selenium.dev")
cheese = driver.find_element(By.ID, "cheese")
cheddar = cheese.find_elements_by_id("cheddar")
cheddar2 = driver.find_element_by_css_selector("#cheese #cheddar")
mucho_cheese = driver.find_elements_by_css_selector("#cheese li")
emailAddressField = driver.find_element(with_tag_name("input").above(cheese))
# above below toLeftOf toRightOf near(距离50px以内)

Node

详细API和源码

const {Builder, By, Key, until} = require('selenium-webdriver');

(async function example() {
    let driver = await new Builder().forBrowser('chrome').build();
    try {
        await driver.get('https://www.baidu.com');
        await driver.findElement(By.name('q')).sendKeys('cheese', Key.ENTER);
        let firstResult = await driver.wait(until.elementLocated(By.css('h3>div')), 10000);
        console.log(await firstResult.getAttribute('textContent'));
    }
    finally{
        driver.quit();
    }
})();

Waits

await driver.wait(until.elementLocated(By.css('p')),10000);
await driver.manage().setTimeouts( { implicit: 10000 } );

Web Element

let ele = driver.findElement(By.name('q'));
let elements = await ele.findElements(By.css('p'));
for(let e of elements) {
  console.log(await e.getText());
  console.log(await e.getAttribute("title"));
  console.log(await e.isEnabled());
  console.log(await e.isSelected());
  console.log(await e.getTagName());
  console.log(await e.getRect());
  console.log(await e.getCssValue('color'));
}

其他


PhantomJS

PhantomJS是一个基于webkit的无界面浏览器,它会把网站加载到内存并执行页面上的JavaScript,配合Selenium可爬取vue渲染后页面

上一篇下一篇

猜你喜欢

热点阅读