如果您对Selenium:是否可以在Selenium中设置WebElement的任何属性值?和selenium.webdriver.remote.webelement.webelement感兴趣,那么
如果您对Selenium:是否可以在Selenium中设置WebElement的任何属性值?和selenium.webdriver.remote.webelement.webelement感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解Selenium:是否可以在Selenium中设置WebElement的任何属性值?的各种细节,并对selenium.webdriver.remote.webelement.webelement进行深入的分析,此外还有关于c# – 是否可以在不安装Selenium Server的情况下使用ISelenium / DefaultSelenium?、org.openqa.selenium.WebElement的实例源码、Selenium API-WebElement 属性、Selenium API-WebElement 方法的实用技巧。
本文目录一览:- Selenium:是否可以在Selenium中设置WebElement的任何属性值?(selenium.webdriver.remote.webelement.webelement)
- c# – 是否可以在不安装Selenium Server的情况下使用ISelenium / DefaultSelenium?
- org.openqa.selenium.WebElement的实例源码
- Selenium API-WebElement 属性
- Selenium API-WebElement 方法
Selenium:是否可以在Selenium中设置WebElement的任何属性值?(selenium.webdriver.remote.webelement.webelement)
我有一个WebElement,我想将其属性值重置为其他值(例如attr
,该属性,并且要将其原始值更改value=1
为new value=10
)。
可能吗?我正在使用Selenium 2.0(WebDriver。)
答案1
小编典典您将必须使用JavascriptExecutor类:
WebDriver driver; // Assigned elsewhereJavascriptExecutor js = (JavascriptExecutor) driver;js.executeScript("document.getElementById(''//id of element'').setAttribute(''attr'', ''10'')");
c# – 是否可以在不安装Selenium Server的情况下使用ISelenium / DefaultSelenium?
这是DefaultSelenium的构造函数:
ISelenium sele = new DefaultSelenium(**serveraddr**,**serverport**,browser,url2test); sele.Start(); sele.open(); ...
似乎我必须在创建ISelenium对象之前安装Selenium Server.
我的情况是,我正在尝试使用C#Selenium构建一个.exe应用程序,它可以在不同的PC上运行,并且不可能在所有PC上安装Selenium Server(你永远不知道哪个是下一个运行应用程序).
有没有人知道如何在不安装服务器的情况下使用ISelenium / DefaultSelenium?
谢谢!
解决方法
1)对于selenium浏览器启动:
DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setbrowserName("safari"); CommandExecutor executor = new SeleneseCommandExecutor(new URL("http://localhost:4444/"),new URL("http://www.google.com/"),capabilities); WebDriver driver = new RemoteWebDriver(executor,capabilities);
2)对于selenium命令:
// You may use any WebDriver implementation. Firefox is used here as an example WebDriver driver = new FirefoxDriver(); // A "base url",used by selenium to resolve relative URLs String baseUrl = "http://www.google.com"; // Create the Selenium implementation Selenium selenium = new WebDriverBackedSelenium(driver,baseUrl); // Perform actions with selenium selenium.open("http://www.google.com"); selenium.type("name=q","cheese"); selenium.click("name=btnG"); // Get the underlying WebDriver implementation back. This will refer to the // same WebDriver instance as the "driver" variable above. WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver(); //Finally,close the browser. Call stop on the WebDriverBackedSelenium instance //instead of calling driver.quit(). Otherwise,the JVM will continue running after //the browser has been closed. selenium.stop();
描述于此:http://seleniumhq.org/docs/03_webdriver.html
谷歌在C#中有类似的东西.没有其他方法可以实现这一目标.
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")); }
Selenium API-WebElement 属性
当我们使用 Selenium 的定位方法定位到元素之后,会返回一个 WebElement 对象(<class ''selenium.webdriver.remote.webelement.WebElement''>
),该对象用来描述 Web 页面上的一个元素,那么,关于元素的常用属性,主要有:
序号 | 方法/属性 | 描述 |
---|---|---|
1 | WebElement.id | 获取元素的标示 |
2 | WebElement.size | 获取元素的宽与高,返回一个字典 |
3 | WebElement.rect | 除了获取元素的宽与高,还获取元素的坐标 |
4 | WebElement.tag_name | 获取元素的标签名称 |
5 | WebElement.text | 获取元素的文本内容 |
WebElement.id
获取元素的标示:
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://www.baidu.com/") # 跳转至百度首页
sleep(1)
element = driver.find_element_by_id("kw") # 定位搜索输入框
print(element.id) # 25c961a3-4d39-4e67-b1f6-b72c89058a29
driver.quit() # 关闭浏览器
WebElement.size
获取元素的宽与高,返回一个字典类型数据:
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://www.baidu.com/") # 跳转至百度首页
sleep(1)
element = driver.find_element_by_id("kw") # 定位搜索输入框
print(element.size) # {''height'': 44, ''width'': 548}
driver.quit() # 关闭浏览器
WebElement.rect
获取元素宽与高的同时,还获取元素的坐标,同样返回的是一个字典类型数据:
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://www.baidu.com/") # 跳转至百度首页
sleep(1)
element = driver.find_element_by_id("kw") # 定位搜索输入框
print(element.rect) # {''height'': 44, ''width'': 548, ''x'': 633, ''y'': 222.234375}
driver.quit() # 关闭浏览器
WebElement.tag_name
获取元素的标签名称:
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://www.baidu.com/") # 跳转至百度首页
sleep(1)
element = driver.find_element_by_id("kw") # 定位搜索输入框
print(element.tag_name) # input
driver.quit() # 关闭浏览器
WebElement.text
获取元素的文本值,无文本内容则返回空字符串:
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://www.baidu.com/") # 跳转至百度首页
sleep(1)
elements = driver.find_elements_by_xpath("//div[@id=''s-top-left'']/a") # 定位搜索输入框
for element in elements:
print(element.text) # 新闻 hao123 地图 视频 贴吧 学术
driver.quit() # 关闭浏览器
总结
Selenium API-WebElement 方法
关于 WebElement 对象的方法,常用的如下表所示:
序号 | 方法/属性 | 描述 |
---|---|---|
1 | WebElement.click() | 单次点击 |
2 | WebElement.send_keys() | 输入指定内容 |
3 | WebElement.clear() | 清空输入框内容 |
4 | WebElement.get_attribute() | 获取元素的属性值 |
5 | WebElement.is_seleted() | 判断元素是否被选中,返回一个 bool 类型值 |
6 | WebElement.is_enabled() | 判断元素是否可用,返回一个 bool 类型值 |
7 | WebElement.is_displayed() | 判断元素是否可见,返回一个 bool 类型值 |
8 | WebElement.value_of_css_property() | 获取元素的 css 属性值 |
WebElement.click()
对定位元素做单次点击操作。
WebElement.send_keys()
向 input
、text
、password
、submit
等文本输入类型输入指定的内容。
WebElement.clear()
清空输入内容。
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://www.baidu.com/") # 跳转至百度首页
sleep(1)
element = driver.find_element_by_id("kw") # 定位搜索输入框
element.send_keys("自动化测试") # 向定位元素输入内容
sleep(1)
element.clear() # 清空输入内容
sleep(1)
element1 = driver.find_element_by_xpath("//div[@s_tab_inner'']/a[4]")
element1.click() # 点击定位元素
sleep(3)
driver.quit()
WebElement.get_attribute()
获取定位元素的属性值:
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://www.baidu.com/") # 跳转至百度首页
sleep(1)
element = driver.find_element_by_xpath("//div[@id=''s-top-left'']/a[5]")
print(element.get_attribute("href")) # http://tieba.baidu.com/
print(element.get_attribute("target")) # _blank
print(element.get_attribute("class")) # mnav c-font-normal c-color-t
driver.quit()
WebElement.is_seleted()
判断元素是否被选中,返回一个 bool 类型值。
WebElement.is_enabled()
判断元素是否可用,返回一个 bool 类型值。
WebElement.is_displayed()
判断元素是否可见,返回一个 bool 类型值。
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://weibo.com/login.php") # 跳转至百度首页
sleep(1)
element = driver.find_element_by_id("login_form_savestate")
print(element.is_displayed()) # True
print(element.is_enabled()) # True
print(element.is_selected()) # True
element.click() # 点击
print(element.is_selected()) # False
driver.quit()
WebElement.value_of_css_property()
获取元素的 css 属性值:
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome() # 打开浏览器
driver.maximize_window() # 浏览器最大化
driver.get("https://www.baidu.com/") # 跳转至百度首页
sleep(1)
element = driver.find_element_by_id("su") # 定位搜索按钮
print(element.value_of_css_property("cursor")) # pointer
print(element.value_of_css_property("background-color")) # rgba(78, 110, 242, 1)
print(element.value_of_css_property("border-radius")) # 0px 10px 10px 0px
print(element.value_of_css_property("color")) # rgba(255, 255, 255, 1)
driver.quit()
总结
今天的关于Selenium:是否可以在Selenium中设置WebElement的任何属性值?和selenium.webdriver.remote.webelement.webelement的分享已经结束,谢谢您的关注,如果想了解更多关于c# – 是否可以在不安装Selenium Server的情况下使用ISelenium / DefaultSelenium?、org.openqa.selenium.WebElement的实例源码、Selenium API-WebElement 属性、Selenium API-WebElement 方法的相关知识,请在本站进行查询。
本文标签: