针对在Selenium中查找WebElement的子节点和selenium获取子节点这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展JavaSelenium封装--RemoteWebElem
针对在Selenium中查找WebElement的子节点和selenium获取子节点这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展Java Selenium封装--RemoteWebElement、org.openqa.selenium.remote.RemoteWebElement的实例源码、org.openqa.selenium.WebElement的实例源码、python – WebElement上的Selenium WebDriver“find_element_by_xpath”等相关知识,希望可以帮助到你。
本文目录一览:- 在Selenium中查找WebElement的子节点(selenium获取子节点)
- Java Selenium封装--RemoteWebElement
- org.openqa.selenium.remote.RemoteWebElement的实例源码
- org.openqa.selenium.WebElement的实例源码
- python – WebElement上的Selenium WebDriver“find_element_by_xpath”
在Selenium中查找WebElement的子节点(selenium获取子节点)
我正在使用Selenium来测试我的Web应用程序,并且可以使用成功找到标签By.xpath
。但是,我时不时需要在该节点内找到子节点。
例:
<div id="a"> <div> <span /> <input /> </div></div>
我可以:
WebElement divA = driver.findElement( By.xpath( "//div[@id=''a'']" ) )
但是现在我需要找到输入,所以我可以这样做:
driver.findElement( By.xpath( "//div[@id=''a'']//input" ) )
但是,到那时,我只拥有了代码divA
,不再具有xpath了……我想做这样的事情:
WebElement input = driver.findElement( divA, By.xpath( "//input" ) );
但是这种功能不存在。我可以这样做吗?
顺便说一句:有时我需要找到一个<div>
具有一定下降节点的。如何在xpath中询问“ <div>
包含<span>
带有文本的''helloworld''
”?
答案1
小编典典根据JavaDocs,您可以执行以下操作:
WebElement input = divA.findElement(By.xpath(".//input"));
如何在xpath中询问“包含带有文本’hello world’的跨度的div标签”?
WebElement elem = driver.findElement(By.xpath("//div[span[text()=''hello world'']]"));
XPath规范对此非常好阅读。
Java Selenium封装--RemoteWebElement
package com.selenium.driver;
import java.sql.SQLException;
import java.util.List;
import org.json.JSONException;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.Select;
public class JSWebElement {
private RemoteWebElement we = null;
private JavascriptExecutor jse = null;
public JSWebElement(){}
public JSWebElement(RemoteWebElement we){
this.we = we;
}
///
///通过元素ID定位元素
///
public JSWebElement findElementById(String using) {
try {
return new JSWebElement((RemoteWebElement)we.findElementById(using));
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
///
///通过元素CSS表达式定位元素
///
public JSWebElement findElementByCssSelector(String using) {
try {
return new JSWebElement((RemoteWebElement)we.findElementByCssSelector(using));
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
///
///通过元素Xpath表达式定位元素
///
public JSWebElement findElementByXPath(String using) {
try {
return new JSWebElement((RemoteWebElement)we.findElementByXPath(using));
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
///
///通过链接的文字定位元素
///
public JSWebElement findElementByLinkText(String using) {
try {
return new JSWebElement((RemoteWebElement)we.findElementByLinkText(using));
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
///
///通过元素DOM表达式定位元素
///
public JSWebElement findElementByDom(String using) {
try {
JavascriptExecutor js = this.getJSE();
WebElement we = (WebElement)js.executeScript(String.format("return %s", using));
return new JSWebElement((RemoteWebElement)we);
}catch (NoSuchElementException e){
return new JSWebElement();
}
}
///
///判断元素是否存在
///
public Boolean isExist(){
if (we != null){
return true;
}else{
return false;
}
}
///
///获取元素的HTML内容
///
public String getHtml(){
return we.getAttribute("outerHTML");
}
///
///获取元素的文本内容
///
public String getText(){
return we.getText();
}
///
///获取元素的value值
///
public String getValue(){
return this.getAttribute("value");
}
///
///获取元素的特定属性值
///
public String getAttribute(String name){
return we.getAttribute(name);
}
///
///向可输入元素发送内容,如:text、textarea、filefield等
///
public void sendKeys(String string){
String old_bg = this.setBackground("yellow");
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
we.sendKeys(string);
this.setBackground(old_bg);
}
///
///判断元素是否可用
///
public boolean isEnabled(){
return we.isEnabled();
}
///
///判断元素是否可见
///
public boolean isVisible(){
return we.isDisplayed();
}
///
///清空可编辑元素的内容。不可编辑元素次操作会抛异常
///
public void clear(){
we.clear();
}
///
///对元素进行点击操作
///
public void click(){
we.click();
}
///
///检查元素的特定属性值
///
public void checkAttr(String attribute, JSWebUtils utils) throws SQLException, JSONException
{
String [] attributes=attribute.split("=", 2);
String actual = this.we.getAttribute(attributes[0]);
if (actual == null){ actual = "null"; }
utils.checkPointBase(actual,attributes[1]);
}
///
///获取元素的CSS值
///
public String getCssValue(String name)
{
return we.getCssValue(name);
}
///
///判断元素是否被选中
///
public boolean isSelected()
{
return we.isSelected();
}
///
///可选元素进行选中操作;如:select
///
public void select(String by, String value) throws Exception
{
if (we.getTagName().equals("select")){
Select select = new Select(we);
if (by.equals("index")){
select.selectByIndex(Integer.parseInt(value));
}else if (by.equals("value")){
select.selectByValue(value);
}else if (by.equals("text")){
select.selectByVisibleText(value);
}
}else{
Exception e = new Exception("The element is not SELECT Object");
throw e;
}
}
///
///对可选中元素进行取消选择操作;如:SELECT in multiple type
///
public void deSelect(String by, String...value) throws Exception
{
if (we.getTagName().equals("select")){
Select select = new Select(we);
if (by.equals("index")){
select.deselectByIndex(Integer.parseInt(value[0]));
}else if (by.equals("value")){
select.deselectByValue(value[0]);
}else if (by.equals("text")){
select.deselectByVisibleText(value[0]);
}else if (by.equals("*")){
select.deselectAll();
}
}else{
Exception e = new Exception("The element is not SELECT Object");
throw e;
}
}
///
///判断下拉框是否为多选
///
public boolean isMultiple() throws Exception
{
if (we.getTagName().equals("select")){
Select select = new Select(we);
if (select.isMultiple()){
return true;
}else{
return false;
}
}else{
Exception e = new Exception("The element is not SELECT Object");
throw e;
}
}
///
///获取select的当前选中值
///
public String getSelectedText() throws Exception
{
if (we.getTagName().equals("select")){
String text = "";
Select select = new Select(we);
List<WebElement> options = select.getAllSelectedOptions();
for (WebElement w : options){
text += w.getText() + "\r\n";
}
return text;
}else{
Exception e = new Exception("The element is not SELECT Object");
throw e;
}
}
///
///判断指定项是否存在
///
public boolean isInclude(String name) throws Exception
{
if (we.getTagName().equals("select")){
Select select = new Select(we);
List<WebElement> options = select.getOptions();
for (WebElement w : options){
if (w.getText().equals(name)){
return true;
}
}
return false;
}else{
Exception e = new Exception("The element is not SELECT Object");
throw e;
}
}
///
///获取元素的tagname
///
public String getTagName(){
return we.getTagName();
}
///
///获取元素的id
///
public String getId(){
return we.getId();
}
///
///获取元素的绝对位置
///
public Point getLocation(){
return we.getLocation();
}
///
///获取元素的出现在屏幕可见区时的位置
///
public Point getLocationOnScreenOnceScrolledIntoView(){
return we.getLocationOnScreenOnceScrolledIntoView();
}
///
///获取元素的坐标
///
public Coordinates getCoordinates(){
return we.getCoordinates();
}
///
///获取元素的大小
///
public Dimension getSize(){
return we.getSize();
}
///
///提交元素所在form的内容
///
public void submit()
{
we.submit();
}
///
///勾选radio、checkbox
///
public void check(String...values) throws Exception
{
if (we.getTagName().equals("input")){
if (we.getAttribute("type").equals("radio")){
WebDriver wd = we.getWrappedDriver();
List<WebElement> wl = wd.findElements(By.name(we.getAttribute("name")));
if (values[0].equals("index")){
wl.get(Integer.parseInt(values[1])).click();
}else if (values[0].equals("value")){
for (WebElement w : wl){
if (w.getAttribute("value").equals(values[1])){
w.click();
break;
}
}
}
}else if (we.getAttribute("type").equals("checkbox")){
if (!we.isSelected()){
we.click();
}
}else{
Exception e = new Exception("The element is not Radio or CheckBox Object");
throw e;
}
}else{
Exception e = new Exception("The element is not INPUT Object");
throw e;
}
}
///
///取消勾选checkbox
///
public void unCheck() throws Exception
{
if (we.getTagName().equals("input") && we.getAttribute("type").equals("checkbox")){
if (we.isSelected()){
we.click();
}
}else{
Exception e = new Exception("The element is not CheckBox Object");
throw e;
}
}
///
///checkbox、radio是否勾选
///
public boolean isChecked(String...values) throws Exception
{
if (we.getTagName().equals("input")){
if (we.getAttribute("type").equals("radio")){
WebDriver wd = we.getWrappedDriver();
List<WebElement> wl = wd.findElements(By.name(we.getAttribute("name")));
if (values[0].equals("index")){
return wl.get(Integer.parseInt(values[1])).isSelected();
}else if (values[0].equals("value")){
for (WebElement w : wl){
if (w.getAttribute("value").equals(values[1])){
return w.isSelected();
}
}
}
return false;
}else if (we.getAttribute("type").equals("checkbox")){
return we.isSelected();
}else{
Exception e = new Exception("The element is not Radio or CheckBox Object");
throw e;
}
}else{
Exception e = new Exception("The element is not INPUT Object");
throw e;
}
}
///
///把元素滚动到可视区
///
public void scroll()
{
this.focus();
}
///
///高亮元素
///
public void highLight() throws InterruptedException
{
this.focus();
JavascriptExecutor js = getJSE();
String old_style = we.getAttribute("style");
for (int i = 0; i < 3; i++) {
js.executeScript("arguments[0].setAttribute(''style'', arguments[1]);", this.we, "background-color: red; border: 2px solid red;" + old_style);
Thread.sleep(500);
js.executeScript("arguments[0].setAttribute(''style'', arguments[1]);", this.we, old_style);
Thread.sleep(500);
}
}
///
///触发元素的特定事件
///
public void fireEvent(String event){
JavascriptExecutor js = getJSE();
js.executeScript(String.format("arguments[0].%s()", event), this.we);
}
///
///使元素获取焦点
///
public void focus(){
// this.we.sendKeys("");
JavascriptExecutor js = getJSE();
js.executeScript("arguments[0].focus();", this.we);
}
///
///对元素执行JavaScript操作;即执行元素的dom操作
///
public void executeJS(String commands){
JavascriptExecutor js = getJSE();
String[] comandArr = commands.split(";");
commands = "";
for (String comand : comandArr){
if (!comand.trim().equals("")){
commands += String.format("arguments[0].%s;", comand);
}
}
if (!commands.equals("")){
js.executeScript(commands, this.we);
}
}
///
///获取原始的RemoteWebElement对象
///
public RemoteWebElement getNativeWebElement(){
return this.we;
}
private JavascriptExecutor getJSE(){
if (this.isExist()){
if (this.jse == null){
WebDriver wd = we.getWrappedDriver();
this.jse = (JavascriptExecutor) wd;
}
}
return jse;
}
private String setBackground(String color){
JavascriptExecutor js = getJSE();
String old_bg = we.getCssValue("background-color");
js.executeScript("arguments[0].style.background = arguments[1];", this.we, color);
return old_bg;
}
}
org.openqa.selenium.remote.RemoteWebElement的实例源码
public void windowTitleWithPercentage() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setTitle("My %Dialog%"); frame.setLocationRelativeto(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); String id1 = ((RemoteWebElement) element1).getId(); // driver.switchTo().window("My %25Dialog%25"); TargetLocator switchTo = driver.switchTo(); switchTo.window("My %Dialog%"); WebElement element2 = driver.findElement(By.name("click-me")); String id2 = ((RemoteWebElement) element2).getId(); AssertJUnit.assertEquals(id1,id2); }
private void fixLocator(SearchContext context,String cssLocator,WebElement element) { if (element instanceof RemoteWebElement) { try { @SuppressWarnings("rawtypes") Class[] parameterTypes = new Class[] { SearchContext.class,String.class,String.class }; Method m = element.getClass().getDeclaredMethod( "setFoundBy",parameterTypes); m.setAccessible(true); Object[] parameters = new Object[] { context,"css selector",cssLocator }; m.invoke(element,parameters); } catch (Exception fail) { //NOOP Would like to log here? } } }
@SuppressWarnings("unchecked") @Override public Object apply(Object result) { if (result instanceof Collection<?>) { Collection<QAFExtendedWebElement> results = (Collection<QAFExtendedWebElement>) result; return Lists.newArrayList(Iterables.transform(results,this)); } result = super.apply(result); if(result instanceof RemoteWebElement){ if(!(result instanceof QAFExtendedWebElement)){ QAFExtendedWebElement ele = newRemoteWebElement(); ele.setId(((RemoteWebElement)result).getId()); return ele; } } return result; }
private void fixLocator(SearchContext context,String.class }; Method m = element.getClass().getDeclaredMethod("setFoundBy",parameters); } catch (Exception e) { logger.error("Something bad happened when fixing locator",e); } } }
@Override @Monitor @RetryFailure(retryCount=3) @JSHandle public WebDriverController uploadFile(Object locator,String path) { LocalFileDetector detector = new LocalFileDetector(); File localFile = detector.getLocalFile(path); ((RemoteWebElement)waitController().waitForElementPresence(locator)).setFileDetector(detector); waitController().waitForElementPresence(locator).sendKeys(localFile.getAbsolutePath()); return this; }
private void fixLocator(SearchContext context,parameters); } catch (Exception fail) { //NOOP Would like to log here? } } }
public void findElementGetsTheSameElementBetweenCalls() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeto(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); String id1 = ((RemoteWebElement) element1).getId(); WebElement element2 = driver.findElement(By.name("click-me")); String id2 = ((RemoteWebElement) element2).getId(); AssertJUnit.assertEquals(id1,id2); }
public void findElementGetsTheSameElementBetweenWindowCalls() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeto(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); String id1 = ((RemoteWebElement) element1).getId(); driver.switchTo().window(titleOfWindow); WebElement element2 = driver.findElement(By.name("click-me")); String id2 = ((RemoteWebElement) element2).getId(); AssertJUnit.assertEquals(id1,id2); }
public void getLocationInView() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeto(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); try { ((RemoteWebElement) element1).getCoordinates().inViewPort(); throw new MissingException(WebDriverException.class); } catch (WebDriverException e) { } }
protected final <T> T waitForPageLoad(Func<T> func) { RemoteWebElement oldHtml = (RemoteWebElement) driver.findElement(By.tagName("html")); T result = func.call(); webdriverwait wait = new webdriverwait(driver,30); wait.until((WebDriver input) -> { RemoteWebElement newHtml = (RemoteWebElement) driver.findElement(By.tagName("html")); return ! newHtml.getId().equals(oldHtml.getId()); }); return result; }
private Class<?> getTypeForProxy() { Class<? extends SearchContext> driverClass = originalDriver.getClass(); Iterable<Map.Entry<Class<? extends SearchContext>,Class<? extends WebElement>>> rules = elementRuleMap.entrySet(); //it will return MobileElement subclass when here is something for (Map.Entry<Class<? extends SearchContext>,Class<? extends WebElement>> e : rules) { //that extends AppiumDriver or MobileElement if (e.getKey().isAssignableFrom(driverClass)) { return e.getValue(); } } //it is compatible with desktop browser. So at this case it returns RemoteWebElement.class return RemoteWebElement.class; }
@Override public WebElement findElement(By by) { WebElement e = getInstance().findElement(by); if (e instanceof RemoteWebElement) { e = new ClickAndWaitRemoteWebElement(e,this); } return e; }
@Override public List<WebElement> findElements(By by) { List<WebElement> list = getInstance().findElements(by); List<WebElement> newList = new ArrayList<>(list.size()); for (WebElement e : list) { if (e instanceof RemoteWebElement) { e = new ClickAndWaitRemoteWebElement(e,this); } newList.add(e); } return newList; }
/** * When send keys is being executed in a input file=type {@link LocalFileDetector} must be configured for remote drivers. Additionally,* the file path is expanded to be absolute * * @param driver used to run commands * @param element receiving keys * @param value to be set to input file type * @return value expanded to absolute path if for input file type. */ private String cleanValuetoSend(WebDriver driver,WebElement element,String value) { if (!StringUtils.equals(element.getAttribute(SeleniumFixture.INPUT_TYPE_ATTRIBUTE),SeleniumFixture.INPUT_TYPE_FILE_VALUE)) { return this.fitnesseMarkup.clean(value); } // set file detector for remote web elements. Local FirefoxDriver uses RemoteWebElement and if (element instanceof RemoteWebElement && !ClassUtils.isAssignable(driver.getClass(),FirefoxDriver.class)) { ((RemoteWebElement) element).setFileDetector(new LocalFileDetector()); } return this.fitnesseMarkup.cleanFile(value).getAbsolutePath(); }
public boolean tapById(String id) { try{ Map<String,?> params = ImmutableMap.of("element",((RemoteWebElement)driver.findElement(By.id(id))).getId()); ((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP,params); }catch(Exception ex) { return false; } return true; }
public boolean tapByXPath(String xpath) { try { Map<String,((RemoteWebElement)driver.findElement(By.xpath(xpath))).getId()); ((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP,params); }catch(Exception ex) { return false; } return true; }
public boolean tap(By by) { try { Map<String,((RemoteWebElement)driver.findElement(by)).getId()); ((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP,params); }catch(Exception ex) { return false; } return true; }
private RemoteWebElement getSelectedRemWebElement() { ComboBox comboBox = new ComboBox(element.getWebElement()); RemoteWebElement selected; try { selected = comboBox.findSelected(); } catch (NoSuchElementException e) { expand(); close(); selected = comboBox.findSelected(); } return selected; }
private RemoteWebElement setowner(RemoteWebElement element) { if (driver != null) { element.setParent(driver); element.setFileDetector(driver.getFileDetector()); } return element; }
private void xpathContext(ExecutionContext script,StreamTokenizer tokenizer) throws Exception { Exception e; stype = SelectionType.None; selector = null; String sval = script.getExpandedString(tokenizer); System.out.println(sval); do { try { selection = (RemoteWebElement) driver.findElement(By.xpath(sval)); if (_not) { _test = _not = false; throw new Exception("not xpath " + sval + " is invalid on line " + tokenizer.lineno()); } selectionCommand = "xpath \"" + sval + "\""; stype = SelectionType.XPath; selector = sval; _test = true; return; } catch(Exception ex) { e = ex; sleep(100); } } while (_waitFor > 0 && (new Date()).getTime() < _waitFor); _waitFor = 0; _test = false; if (!_if) { if (_not) { _test = true; selection = null; _not = false; return; } throw new Exception("xpath " + sval + " is invalid on line " + tokenizer.lineno() + " " + e.getMessage()); } }
private void selectContext(StreamTokenizer tokenizer,ExecutionContext script) throws Exception { Exception e; stype = SelectionType.None; selector = null; String sval = script.getExpandedString(tokenizer); System.out.println(sval); do { try { selection = (RemoteWebElement) driver.findElement(By.cssSelector(sval)); if (_not) { _test = _not = false; throw new Exception("not selector " + sval + " is invalid on line " + tokenizer.lineno()); } selectionCommand = "select \"" + sval + "\""; stype = SelectionType.Select; selector = sval; _test = true; return; } catch(Exception ex) { e = ex; sleep(100); } } while (_waitFor > 0 && (new Date()).getTime() < _waitFor); _waitFor = 0; _test = false; if (!_if) { if (_not) { _test = true; selection = null; selector = null; _not = false; return; } throw new Exception("selector " + sval + " is invalid on line " + tokenizer.lineno() + " " + e.getMessage()); } }
private void setContextToField(ExecutionContext script,StreamTokenizer tokenizer) throws Exception { Exception e; String sval = script.getExpandedString(tokenizer); System.out.println(sval); String query = "//*[@test-id='"+sval+"']"; stype = SelectionType.None; selector = null; do { try { selection = (RemoteWebElement) driver.findElement(By.xpath(query)); if (_not) { _test = _not = false; throw new Exception("not test-id " + sval + " is invalid on line " + tokenizer.lineno()); } selectionCommand = "field \"" + sval + "\""; stype = SelectionType.Field; selector = query; _test = true; return; } catch(Exception ex) { e = ex; sleep(100); } } while (this._waitFor > 0 && (new Date()).getTime() < this._waitFor); _waitFor = 0; _test = false; if (!_if) { if (_not) { _test = true; selection = null; _not = false; return; } throw new Exception("field reference " + sval + " is invalid on line " + tokenizer.lineno() + " " + e.getMessage()); } }
protected void fillFileBox(RemoteWebElement fileBoxElement,String fileName) { if (fileName.isEmpty()) { fileBoxElement.clear(); } else { fileBoxElement.setFileDetector(new UselessFileDetector()); String newFilePath = new File(fileName).getAbsolutePath(); fileBoxElement.sendKeys(newFilePath); } }
@Override public Object apply(Object result) { if (result instanceof RemoteWebElement && !(result instanceof CachingRemoteWebElement)) { RemoteWebElement originalElement = (RemoteWebElement) result; result = createCachingWebElement(originalElement); } return super.apply(result); }
protected CachingRemoteWebElement createCachingWebElement(RemoteWebElement originalElement) { CachingRemoteWebElement element = new CachingRemoteWebElement(originalElement); // ensure we always set the correct parent and file detector element.setParent(driver); element.setFileDetector(driver.getFileDetector()); return element; }
@Override public Object generate(Object target,Method method,Object... params) { StringBuilder sb = new StringBuilder(); sb.append(SessionContext.getSession().getWebDriver().toString()); sb.append(" ").append(method.getName()); for (Object param : params) if (param instanceof WebElement && !(SessionContext.getSession().getWebDriver() instanceof EventFiringWebDriver)) sb.append(" ").append(((RemoteWebElement) param).getId()); else if (param instanceof WebElement && SessionContext.getSession().getWebDriver() instanceof EventFiringWebDriver) { sb.append(" ").append(((WebElement) param).getLocation()); } else { sb.append(" ").append(param.toString()); } return sb.toString(); }
@Ignore @Test public void deleteallNotes() throws CandybeanException { openNotes(); List<WebElement> notes = iface.wd.findElements(By .id("com.evernote:id/title")); while (notes.size() != 0) { WebElement note = notes.get(0); HashMap<String,String> values = new HashMap<String,String>(); values.put("element",((RemoteWebElement) note).getId()); ((JavascriptExecutor) iface.wd).executeScript("mobile: longClick",values); iface.pause(1000); WebElement footer = ((RemoteWebDriver) iface.wd) .findElementById("com.evernote:id/efab_menu_footer"); List<WebElement> footerItems = footer.findElements(By .className("android.widget.ImageButton")); WebElement moreOptions = footerItems.get(footerItems.size() - 1); moreOptions.click(); iface.pause(1000); WebElement deleteButton = iface.wd.findElements( By.id("com.evernote:id/item_title")).get(5); deleteButton.click(); iface.pause(1000); WebElement deleteConfirmation = iface.wd.findElement(By .id("android:id/button1")); deleteConfirmation.click(); iface.pause(1000); notes = iface.wd.findElements(By.id("com.evernote:id/title")); } assertEquals(iface.wd.findElements(By.id("com.evernote:id/title")).size(),0); }
private void disableAutoComplete(){ // display the settings in Google Earth Engine Code Editor (this emulates clicking on the settings icon) webDriverGee.findElementByClassName("settings-menu-button").click(); // Get the Div that is the parent of the one with text that contains Autocomplete RemoteWebElement autocompleteButton = (RemoteWebElement) webDriverGee.findElementByXPath("//div[contains(text(),\"Autocomplete\")]/.."); if(isAutocompleChecked(autocompleteButton)){ // disable the Autocomplete of special characters autocompleteButton.click(); } }
private final JavascriptExecutor getJavascriptExecutor(SearchContext context) { JavascriptExecutor jse; if (context instanceof RemoteWebElement) { jse = (JavascriptExecutor) ((RemoteWebElement) context).getWrappedDriver(); } else { jse = (JavascriptExecutor) context; } return jse; }
private Map<String,Object> getTouchParameters(WebElement element,int x,int y) { Map<String,Object> params = Maps.newHashMap(); if (element != null) { params.put("element",((RemoteWebElement) element).getId()); } params.put("x",x); params.put("y",y); return params; }
/** * Get the values of all table cells.</br> * * <b>Note:</b> If a table cell contains a checkBox - we will return 'checked' or 'notchecked' value. * * @return a two dimensional array containing all table cell values */ @PublicAtsApi public String[][] getAllValues() { new RealHtmlElementState(this).waitToBecomeExisting(); WebElement table = RealHtmlElementLocator.findElement(this); String scriptForHtml = generateScriptForGettingTableContent(".innerHTML"); Object returnedHtmlValue = ((JavascriptExecutor) webDriver).executeScript(scriptForHtml,table); String scriptForObjects = generateScriptForGettingTableContent(""); Object returnedobjectsValue = ((JavascriptExecutor) webDriver).executeScript(scriptForObjects,table); String[][] tableData = null; if (returnedHtmlValue != null && returnedHtmlValue instanceof List && returnedobjectsValue != null && returnedobjectsValue instanceof List) { List<?> htmlTable = (List<?>) returnedHtmlValue; List<?> objectsTable = (List<?>) returnedobjectsValue; // allocate space for a number of rows tableData = new String[htmlTable.size()][]; for (int iRow = 0; iRow < htmlTable.size(); iRow++) { if (htmlTable.get(iRow) instanceof List) { List<?> htmlRow = (List<?>) htmlTable.get(iRow); List<?> objectsRow = (List<?>) objectsTable.get(iRow); // allocate space for the cells of the current row tableData[iRow] = new String[htmlRow.size()]; for (int iColumn = 0; iColumn < htmlRow.size(); iColumn++) { Object htmlWebElement = htmlRow.get(iColumn); Object objectWebElement = objectsRow.get(iColumn); // some data cannot be presented in textual way - for example a checkBox String htmlValueString = htmlWebElement.toString() .toLowerCase() .replace("\r","") .replace("\n",""); if (htmlValueString.matches(".*<input.*type=.*[\"|']checkBox[\"|'].*>.*")) { // We assume this is a checkBox inside a table cell. // We will return either 'checked' or 'notchecked' tableData[iRow][iColumn] = htmlValueString.contains("checked") ? "checked" : "notchecked"; } else { // proceed in the regular way by returning the data visible to the user tableData[iRow][iColumn] = ((RemoteWebElement) objectWebElement).getText(); } } } } } else { log.warn("We Could not get the content of table declared as: " + this.toString()); } return tableData; }
/** * Wrap WebElement in MobileElement * */ private static MobileElement w(WebElement element) { return new MobileElement((RemoteWebElement) element,driver); }
public static <T extends AdfComponent> T forElement(WebElement element) { RemoteWebElement rwe = (RemoteWebElement) element; RemoteWebDriver rwd = (RemoteWebDriver) rwe.getWrappedDriver(); String clientid = (String) rwd.executeScript(JS_FIND_ANCESTOR_COMPONENT,element); return forClientId(rwd,clientid); }
public RemoteWebElement getWebElement() { return this.webElement; }
public NativeAppElement(NativeAppDriver nativeAppDriver,By byLocator,WebElement webElement) { this.webElement = (RemoteWebElement) webElement; this.nativeAppDriver = nativeAppDriver; this.byLocator = byLocator; }
public void fillProfilePic(String fileName) { showPictureEditor(); RemoteWebElement ele = (RemoteWebElement) browser.driver.findElement(By.id("studentPhoto")); fillFileBox(ele,fileName); }
public CachingRemoteWebElement(RemoteWebElement element) { if (element != null) { setId(element.getId()); } }
/** * If an exception has thrown by selenium,this methods save a screen * capture. * * @param pjp ProceedingJoinPoint * @return Object object * @throws Throwable exception */ @Around(value = "exceptionCallpointcut()") public Object aroundExceptionCalls(ProceedingJoinPoint pjp) throws Throwable { Object retVal = null; try { retVal = pjp.proceed(); return retVal; } catch (Throwable ex) { WebDriver driver = null; if (ex instanceof WebDriverException) { logger.info("Got a selenium exception"); if (!(pjp.getThis() instanceof WebDriver)) { throw ex; } driver = (WebDriver) pjp.getThis(); } else if ((pjp.getTarget() instanceof SeleniumAssert) && (ex instanceof AssertionError)) { logger.info("Got a SeleniumAssert response"); SeleniumAssert as = (SeleniumAssert) pjp.getTarget(); Class<?> c = as.getClass().getSuperclass(); Field actual = c.getDeclaredField("actual"); actual.setAccessible(true); Object realActual = actual.get(as); if (realActual instanceof WebDriver) { driver = (WebDriver) actual.get(as); } else if (realActual instanceof ArrayList) { if (((ArrayList) realActual).get(0) instanceof RemoteWebElement) { driver = ((RemoteWebElement) ((ArrayList) realActual).get(0)).getWrappedDriver(); } } else if ((realActual instanceof PrevIoUsWebElements) || (realActual instanceof Boolean) || (realActual instanceof String) || (realActual == null)) { driver = ((CommonG) ((SeleniumAssert) pjp.getTarget()).getCommonspec()).getDriver(); } else if (realActual instanceof RemoteWebElement) { driver = ((RemoteWebElement) actual.get(as)).getWrappedDriver(); } } if (driver != null) { logger.info("Trying to capture screenshots..."); CommonG common = null; if ((pjp.getThis() instanceof ThenGSpec) && (((ThenGSpec) pjp.getThis()).getCommonSpec() != null)) { common = ((ThenGSpec) pjp.getThis()).getCommonSpec(); } else if ((pjp.getTarget() instanceof SeleniumAssert) && ((SeleniumAssert) pjp.getTarget()).getCommonspec() != null) { common = ((CommonG) ((SeleniumAssert) pjp.getTarget()).getCommonspec()); } else { logger.info("Got no Selenium driver to capture a screen"); throw ex; } common.captureEvidence(driver,"framehtmlSource","assert"); common.captureEvidence(driver,"htmlSource","screenCapture","assert"); logger.info("Screenshots are available at target/executions"); } else { logger.info("Got no Selenium driver to capture a screen"); } throw ex; } }
public boolean isAutocompleChecked(RemoteWebElement autocompleteButton) { String buttonChecked = autocompleteButton.getAttribute("aria-checked"); return buttonChecked.equals("true" ); }
org.openqa.selenium.WebElement的实例源码
public void click() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeto(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); element1.click(); AssertJUnit.assertTrue(buttonClicked); buttonClicked = false; new Actions(driver).click().perform(); AssertJUnit.assertTrue(buttonClicked); AssertJUnit.assertTrue(buttonMouseActions.toString().contains("clicked(1)")); buttonMouseActions.setLength(0); new Actions(driver).contextClick().perform(); AssertJUnit.assertTrue(buttonMouseActions.toString(),buttonMouseActions.toString().contains("pressed(3-popup)")); }
/** * @return how many rows this table has */ @Override @PublicAtsApi public int getRowCount() { new HiddenHtmlElementState(this).waitToBecomeExisting(); String css = this.getElementProperty("_css"); List<WebElement> elements = null; if (!StringUtils.isNullOrEmpty(css)) { css += " tr"; elements = webDriver.findElements(By.cssSelector(css)); } else { // get elements matching the following xpath elements = webDriver.findElements(By.xpath(properties.getInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR) + "/tr | " + properties.getInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR) + "/*/tr")); } return elements.size(); }
private static WebElement getElement(WebDriver driver,By by,int current){ WebElement element = null; while(true) { try { element = driver.findElement(by); } catch (Exception e){ //might happen due to Github blocking crawling try { long time = 60_000; System.out.println("Cannot find -> "+by.toString()+"\n Going to wait for "+time+"ms"); Thread.sleep(time); openPagedSearchResult(driver,current); } catch (InterruptedException e1) { } continue; } break; } return element; }
/** * Drag and drop an element on top of other element * @param targetElement the target element */ @Override @PublicAtsApi public void dragAndDropTo( HtmlElement targetElement ) { new RealHtmlElementState(this).waitToBecomeExisting(); WebElement source = RealHtmlElementLocator.findElement(this); WebElement target = RealHtmlElementLocator.findElement(targetElement); Actions actionBuilder = new Actions(webDriver); Action dragAndDropAction = actionBuilder.clickAndHold(source) .movetoElement(target,1,1) .release(target) .build(); dragAndDropAction.perform(); // drops the source element in the middle of the target,which in some cases is not doing drop on the right place // new Actions( webDriver ).dragAndDrop( source,target ).perform(); }
public void isEnabled() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeto(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); AssertJUnit.assertTrue(element1.isEnabled()); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { button.setEnabled(false); } }); EventQueueWait.waitTilldisabled(button); AssertJUnit.assertFalse(element1.isEnabled()); }
@Override public Object decorate(ClassLoader loader,Field field) { By selector = new Annotations(field).buildBy(); if (selector instanceof ByIdOrName) { // throw new IllegalArgumentException("Please define locator for " + field); return decorateWithAppium(loader,field); } else if (WebElement.class.isAssignableFrom(field.getType())) { return ElementFinder.wrap(searchContext,selector,0); } else if (ElementsCollection.class.isAssignableFrom(field.getType())) { return new ElementsCollection(new BySelectorCollection(searchContext,selector)); } else if (ElementsContainer.class.isAssignableFrom(field.getType())) { return createElementsContainer(selector,field); } else if (isDecoratableList(field,ElementsContainer.class)) { return createElementsContainerList(field); } else if (isDecoratableList(field,SelenideElement.class)) { return SelenideElementListProxy.wrap(factory.createLocator(field)); } return decorateWithAppium(loader,field); }
public void atc() { webdriverwait wait = new webdriverwait(driver,300L); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@and (.//span[text()[contains(.,'Size')]] or .//span[text()[contains(.,'size')]])]"))); int index = new Random().nextInt(sizes.length); String sizetoPick = Double.toString(sizes[index]); for(WebElement e : driver.findElements(By.xpath("//div[@and .//ul[.//li[.//span[text()[contains(.,'size')]]]]]/ul/li"))) { String size = e.getText().trim(); if(size != null && size.equals(sizetoPick)) { e.click(); break; } } }
/** * select a value * * @param value the value to select */ @Override @PublicAtsApi public void setValue( String value ) { new RealHtmlElementState(this).waitToBecomeExisting(); try { WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); select.selectByVisibleText(value); } catch (NoSuchElementException nsee) { throw new SeleniumOperationException("Option with label '" + value + "' not found. (" + this.toString() + ")"); } UiEngineUtilities.sleep(); }
private WebElement get_password() { WebElement element = null; if (WebUtilities.waitForElementToAppear(driver,password,logger)) { element = password; } return element; }
protected void waitForElementToNotExist(WebElement element) { new webdriverwait(getDriverProxy(),20) .withMessage("Timed out waiting for element to not exist.") .until((WebDriver d) -> { boolean conditionMet = false; try { // We don't really care whether it's displayed or not,just if it exists. element.isdisplayed(); } catch (NoSuchElementException | StaleElementReferenceException e) { conditionMet = true; } return conditionMet; }); }
/** * Posts the given message to the brain chat. * * @param message * The message to post */ public void postMessage(final String message) { updateLastUsage(); switchToWindow(); switchToFrame(CHAT_INPUT_FRAME_NAME); final WebElement input = new NamePresenceWait(this.mDriver,CHAT_INPUT_NAME).waitUntilCondition(); input.sendKeys(message); input.sendKeys(Keys.ENTER); }
public static void hoverMouSEOnWebElement(WebDriver driver,ExtentTest logger,WebElement element) { try { Actions action = new Actions(driver); action.movetoElement(element).build().perform(); } catch (Exception e) { logger.log(LogStatus.ERROR,"Error hovering over the element</br>" + e.getCause()); } }
/** * Remove hidden elements from specified list * * @param elements list of elements * @return 'true' if no visible elements were found; otherwise 'false' */ public static boolean filterHidden(List<WebElement> elements) { Iterator<WebElement> iter = elements.iterator(); while (iter.hasNext()) { if ( ! iter.next().isdisplayed()) { iter.remove(); } } return elements.isEmpty(); }
public void clicksOnMenus() throws Throwable { driver = new JavaDriver(); List<WebElement> menus = driver.findElements(By.cssSelector("menu")); int i = 0; clicksOnMenu(menus,i++,"Menu 1"); clicksOnMenu(menus,"Menu 2"); clicksOnMenu(menus,"Menu 3"); }
@Override public boolean checkCssClassDoesNotContain(WebElement w,String... args) throws Exception { startTime(); boolean result = currentPage.checkCssClassDoesNotContain(w,args); this.setNextPage(); return result; }
/** * Simulate Tab key */ @Override @PublicAtsApi public void presstabKey() { new RealHtmlElementState(this).waitToBecomeExisting(); WebElement element = RealHtmlElementLocator.findElement(this); element.sendKeys(Keys.TAB); }
public WebElement findElement(SearchContext element,String objectKey,String pageKey,String Attribute,FindType condition) { pageName = pageKey; objectName = objectKey; findType = condition; return getElementFromList(findElements(element,getoRObject(pageKey,objectKey),Attribute)); }
@Test public void testAssertElementAttribute() { final WebElement webElement = Mockito.mock(WebElement.class); Mockito.when(webElement.getAttribute(ArgumentMatchers.any())).thenReturn(null).thenReturn("value"); Mockito.when(mockDriver.findElement(ArgumentMatchers.any())).thenReturn(webElement); assertElementAttribute("value",null,null); }
void getAttributes() throws Throwable { driver = new JavaDriver(); WebElement textArea = driver.findElement(By.cssSelector("text-area")); AssertJUnit.assertEquals("true",textArea.getAttribute("editable")); textArea.sendKeys("Systems",Keys.SPACE); String prevIoUsText = textArea.getText(); textArea.clear(); textArea.sendKeys("Jalian" + prevIoUsText); }
public List<Attribute> attributes() { List<Attribute> rows = new ArrayList<>(); for (WebElement tr : this.trs) { rows.add(new Attribute(tr)); } this.attributes.addAll(rows); return this.attributes; }
private String getMetaTagNamed(WebDriver driver,String name) { JsUtility.injectglueLib(driver); String script = JsUtility.getScriptResource("requireMetaTagByName.js"); try { WebElement response = JsUtility.runAndReturn(driver,script,name); return response.getAttribute("content"); } catch (WebDriverException e) { throw JsUtility.propagate(e); } }
@Override public WebElement findElement(SearchContext driver) { if(!(driver instanceof WebDriver)) { throw new IllegalArgumentException("Argument must be instanceof WebDriver."); } WebDriver webDriver = (WebDriver) driver; webDriver = engine.turnToRootDriver(webDriver); if(!iframeWait(webDriver,getTimeout(),getValue())) { webDriver.switchTo().frame(getValue()); } return null; }
@Test public void testChangeElementSelectedBy() { driver.get(utils.getResourceURI("ElementSearch.html")); utils.injectScripts(Optional.<String> empty()); WebElement target = wait.until( ExpectedConditions.visibilityOf(driver.findElement(By.tagName("h1")))); utils.highlight(target); // Act utils.inspectElement(target); // Assert List<String> labels = driver .findElements(By.cssSelector("form#SWDForm label[for]")).stream() .map(e -> e.getAttribute("for")).collect(Collectors.toList()); String lastLabel = null; Collections.sort(labels,String.CASE_INSENSITIVE_ORDER); for (String label : labels) { utils.sleep(100); WebElement radioElement = wait.until(ExpectedConditions.visibilityOf( driver.findElement(By.xpath(String.format("//*[@id='%s']",label))))); assertthat(radioElement,notNullValue()); radioElement.click(); lastLabel = label; } utils.completeVisualSearch("changing strategy attribute"); // Assert String payload = utils.getPayload(); assertFalse(payload.isEmpty()); Map<String,String> details = new HashMap<>(); utils.readData(payload,Optional.of(details)); verifyNeededKeys(details); verifyEntry(details,"ElementSelectedBy",lastLabel); }
@Override public WebElement getElementByName(String elementName,int nth,WebDriver webDriver) { List<WebElement> elements = webDriver.findElements(pageElements.get(elementName)); if (elements.size() == 0) { return null; } return elements.get(nth); }
@Test public void ontest() { final WebDriver webDriver = Mockito.mock(WebDriver.class); final WebElement webElement = Mockito.mock(WebElement.class); final Type type = new Type(webDriver,"text",() -> {}); final By byId = By.id("id"); Mockito.when(webDriver.findElement(byId)).thenReturn(webElement); type.on(byId); Mockito.verify(webElement).sendKeys("text"); }
public void getLocation() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeto(null); frame.setVisible(true); } }); WebElement element1 = driver.findElement(By.name("click-me")); Point location = element1.getLocation(); java.awt.Point p = EventQueueWait.call(button,"getLocation"); AssertJUnit.assertEquals(p.x,location.x); AssertJUnit.assertEquals(p.y,location.y); }
private WebElement get_signInButton() { WebElement element = null; if (WebUtilities.waitForElementToAppear(driver,signInButton,logger)) { element = signInButton; } return element; }
/** * Shuts this instance down and frees all used resources. */ public void shutdown() { switchToWindow(); switchToFrame(CHAT_INPUT_FRAME_NAME); final WebElement logoutAnchor = new CSSSelectorPresenceWait(this.mDriver,logoUT_ANCHOR).waitUntilCondition(); logoutAnchor.click(); this.mDriver.close(); }
@Then("I can download(?: following files)?:") public void iCanDownload(final DataTable downloadTitles) throws Throwable { for (List<String> downloadLink : downloadTitles.asLists(String.class)) { String linkText = downloadLink.get(0); String linkFileName = downloadLink.get(1); WebElement downloadElement = sitePage.findElementWithTitle(linkText); assertthat("I can find download link with title: " + linkText,downloadElement,is(notNullValue())); String url = downloadElement.getAttribute("href"); assertEquals("I can find link with expected URL for file " + linkFileName,URL + urlLookup.lookupUrl(linkFileName),url); if (acceptanceTestProperties.isHeadlessMode()) { // At the moment of writing,there doesn't seem to be any easy way available to force Chromedriver // to download files when operating in headless mode. It appears that some functionality has been // added to DevTools but it's not obvIoUs how to trigger that from Java so,for Now at least,// we'll only be testing file download when operating in a full,graphical mode. // // See bug report at https://bugs.chromium.org/p/chromium/issues/detail?id=696481 and other reports // available online. log.warn("Not testing file download due to running in a headless mode,will just check link is present."); } else { // Trigger file download by click the <a> tag. sitePage.clickOnElement(downloadElement); final Path downloadedFilePath = Paths.get(acceptanceTestProperties.getDownloadDir().toString(),linkFileName); waitUntilFileAppears(downloadedFilePath); } } }
/** * Simulate mouse double click action */ @Override @PublicAtsApi public void doubleClick() { new RealHtmlElementState(this).waitToBecomeExisting(); WebElement element = RealHtmlElementLocator.findElement(this); new Actions(webDriver).doubleClick(element).perform(); }
@Test public void testAssertSelectedText() { final WebElement webElement = Mockito.mock(WebElement.class); Mockito.when(mockDriver.findElement(ArgumentMatchers.any())).thenReturn(webElement); Mockito.when(webElement.getTagName()).thenReturn("select"); final List<WebElement> items = new ArrayList<>(); items.add(webElement); Mockito.when(webElement.findElements(ArgumentMatchers.any())).thenReturn(items); Mockito.when(webElement.isSelected()).thenReturn(true); Mockito.when(webElement.getText()).thenReturn("text"); assertSelectedText("text",null); }
public static void main(String[] args) throws Exception { // Create a DesiredCapabilities object to request specific devices from the WebDriver server. // A udid can be optionally specified,otherwise an arbitrary device is chosen. DesiredCapabilities caps = new DesiredCapabilities(); // caps.setCapability("uuid",udid); // Start a WebDriver session. The local machine has to be running the SafariDriverServer,or // change localhost below to an IP running the SafariDriverServer. driver = new RemoteWebDriver(new URL("http://localhost:5555/wd/hub"),caps); // Connect to a URL driver.get("http://www.google.com"); // Interact with the web page. In this example use case,the Webdriver API is used to find // specific elements,test a google search and take a screenshot. driver.findElement(By.id("hplogo")); // Google New York WebElement mobileSearchBox = driver.findElement(By.id("lst-ib")); mobileSearchBox.sendKeys("New York"); WebElement searchBox; try { searchBox = driver.findElement(By.id("tsbb")); } catch (NoSuchElementException e) { searchBox = driver.findElement(By.name("btnG")); } searchBox.click(); takeScreenshot(); driver.navigate().refresh(); takeScreenshot(); // Quit the WebDriver instance on completion of the test. driver.quit(); driver = null; }
@Override public void selectByAnotherTextThan(final String text) { final org.openqa.selenium.support.ui.Select select = wrappedSelect(); final List<WebElement> options = select.getoptions(); for (int i = options.size() - 1; i >= 0; i--) { final WebElement each = options.get(i); if (!each.getText().equals(text)) { select.selectByIndex(i); return; } } }
public void tableCellEditSelectByProps() throws Throwable { driver = new JavaDriver(); String selector = "{ \"select\": \"{2,Sport}\" }"; WebElement cell = driver.findElement(By.cssSelector("table::select-by-properties('" + selector + "')::editor")); AssertJUnit.assertEquals("text-field",cell.getTagName()); cell.clear(); cell.sendKeys("Hello World",Keys.ENTER); cell = driver.findElement(By.cssSelector("table::mnth-cell(3,3)")); AssertJUnit.assertEquals("Hello World",cell.getText()); cell = driver.findElement(By.cssSelector("table::mnth-cell(3,5)")); AssertJUnit.assertEquals("boolean-renderer",cell.getTagName()); cell = driver.findElement(By.cssSelector("table::mnth-cell(3,5)::editor")); AssertJUnit.assertEquals("check-Box",cell.getTagName()); }
@Override public boolean clickElement(WebElement w) throws Exception { startTime(); boolean result = currentPage.clickElement(w); this.setNextPage(); return result; }
@After public void closeApp() { WebElement fileMenu = driver.findElement(By.xpath("//Menu[@caption='File']")); fileMenu.click(); WebElement exit = driver.findElement(By.xpath("//MenuItem[@caption='Exit']")); exit.click(); driver.quit(); }
private void assertClicksOnMenuItemsInSubMenu(WebElement menu) throws Throwable { menu.click(); List<WebElement> includeSubMenus = driver.findElements(By.cssSelector("menu")); AssertJUnit.assertEquals(4,includeSubMenus.size()); WebElement subMenu = includeSubMenus.get(3); AssertJUnit.assertEquals("Submenu",subMenu.getText()); List<WebElement> menuItems = driver.findElements(By.cssSelector("menu-item")); AssertJUnit.assertEquals(3,menuItems.size()); menu.click(); assertClicks(menu,subMenu,3); }
@Step @Then("значение динамического поля \"$field\" равно \"$expectedValue\"") public void stepCheckValueInDynamicFields(@Named("$field") String field,@Named("$expectedValue") String expectedValue) { IElement parent = getCurrentPage().getElementByName(field); IElement nested = pageProvider.getPageByName(DYNAMIC_FIELDS_PAGE_NAME).getElementByName(EDIT_TEXT_NAME); WebElement elementFound = finder.findnestedWebElement(parent,nested); String actualElement = elementFound.getText(); assertEquals(format("Значение поля [%s] не соответствует ожидаемому [%s]",actualElement,expectedValue),expectedValue,actualElement); }
public void elementSendKeys() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeto(null); frame.setVisible(true); } }); AssertJUnit.assertEquals("",EventQueueWait.call(textField,"getText")); WebElement element1 = driver.findElement(By.name("text-field")); element1.sendKeys("Hello"," ","World"); AssertJUnit.assertEquals("Hello World","getText")); }
public void getheader() throws Throwable { driver = new JavaDriver(); WebElement header = driver.findElement(By.cssSelector("table::header")); AssertJUnit.assertEquals(5 + "",header.getAttribute("count")); WebElement header2 = driver.findElement(By.cssSelector("table-header")); AssertJUnit.assertEquals(5 + "",header2.getAttribute("count")); }
python – WebElement上的Selenium WebDriver“find_element_by_xpath”
我正在尝试使用以下行查找元素:
elements = driver.find_elements_by_xpath("//div[@]")
一旦我有了元素,我知道有两个“显示”,我希望能够使用第二个,并在其中找到一个特定的元素,如下所示:
title = elements[1].find_element_by_xpath("//div[@]")
但是,它总是恢复使用第一个.我已经介入了它,它正在为“显示”找到2个元素,所以我不确定我做错了什么.
任何帮助将不胜感激.
elements = driver.find_elements_by_xpath("//div[@]")
title = elements[1].find_elements_by_xpath(".//div[@]")
我们今天的关于在Selenium中查找WebElement的子节点和selenium获取子节点的分享就到这里,谢谢您的阅读,如果想了解更多关于Java Selenium封装--RemoteWebElement、org.openqa.selenium.remote.RemoteWebElement的实例源码、org.openqa.selenium.WebElement的实例源码、python – WebElement上的Selenium WebDriver“find_element_by_xpath”的相关信息,可以在本站进行搜索。
本文标签: