While writing selenium testcases for a webapplication I'm having trouble with the xpath selector. The element of the HTML-code which should be clicked on by Selenium is the following:
<a title="Voeg een vak toe" href="#" onclick="javascript:$.colorbox({width:818,href:'/olo-cleanjump/profiel/addVakForm'}); return false;">
<p class="add">
<img class="add-icon" src="/olo-cleanjump/static/images/icon_add.png"/>
Voeg vak toe
</p>
</a>
The Selenium IDE plugin for firefox gives me the following selenium code for this:
driver.findElement(By.cssSelector("p.add")).click();
The addVakForm javascript function that is called by this link opens a colorbox with the following HTML (I shortened it, there are around 30 similar div's with class "lesboek_popup") inside:
<div id="cboxLoadedContent" style="display: block; width: 776px; overflow: auto; height: 653px;">
<div id="profielpagina_add">
<h2>Voeg een vak toe aan je profiel</h2>
<div class="lesboek_popup">
<a class="content" href="/olo-cleanjump/profiel/addvak/120776">
<img src="" alt="">
</a>
<p class="caption">
Engels
</p>
</div>
<div class="lesboek_popup">
<a class="content" href="/olo-cleanjump/profiel/addvak/120786">
<img src="" alt="">
</a>
<p class="caption">
Biologie
</p>
</div>
</div>
For the test I want to open the 'Biologie' link. Selenium IDE got me the following selenium code to do this
driver.findElement(By.xpath("//div[#id='profielpagina_add']/div[20]/a")).click();
to select this biology link element.
Based on this I wrote the following testcase:
Test
public void testAddRemoveVak() throws Exception {
this.get("");
// vak 1 toevoegen
driver.findElement(By.cssSelector("p.add")).click();
driver.findElement(By.xpath("//div[#id='profielpagina_add']/div[20]/a")).click();
// vak 2 toevoegen
driver.findElement(By.cssSelector("p.add")).click();
driver.findElement(By.xpath("//div[#id='profielpagina_add']/div[20]/a")).click();
assertEquals(driver.findElements(By.xpath("//li[#class='vak']")).size(), 2);
// vak 2 verwijderen
this.get("profiel/removevak/120791");
assertEquals(driver.findElements(By.xpath("//li[#class='vak']")).size(), 1);
}
The part
driver.findElement(By.cssSelector("p.add")).click();
actually was successful, so after this call the colorbox should be loaded. However the
driver.findElement(By.xpath("//div[#id='profielpagina_add']/div[20]/a")).click();
causes an NoSuchElementException, while this element definitely is present in the colorbox when I check for myself (the call/xpath was even autogenerated by Selenium IDE). Does anyone have a clue what may cause the NoSuchElementException?
Probably you should wait when your popup appears. Try to use Implicit waits
WebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
Also instead of xpath you can use driver.FindElement(By.LinkText("Biologie")).click() if it the only link with text Biologie on your page
Related
element code:
<div class="col col-2"><div class="v-input v-input--is-focused theme--light v-text-field v-text-field--is-booted v-select primary--text"><div class="v-input__control"><div role="button" aria-haspopup="listbox" aria-expanded="false" aria-owns="list-65" class="v-input__slot"><div class="v-select__slot"><label for="input-65" class="v-label v-label--active theme--light primary--text" style="left: 0px; right: auto; position: absolute;">Narystė</label><div class="v-select__selections"><input id="input-65" readonly="readonly" type="text" aria-readonly="false" autocomplete="off"></div><div class="v-input__append-inner"><div class="v-input__icon v-input__icon--append"><i aria-hidden="true" class="v-icon notranslate material-icons theme--light primary--text">arrow_drop_down</i></div></div><input type="hidden" value="[object Object]"></div><div class="v-menu"><!----></div></div><div class="v-text-field__details"><div class="v-messages theme--light primary--text"><div class="v-messages__wrapper"></div></div></div></div></div></div>
in screen you can see, that entered xpath is only one.
Here is code, where i have entered the same xpath, but getting error like this:
private static final By naryste = By.xpath("//*[contains(#class,'v-label v-label--active theme--light primary--text') and contains(text(),'Narystė')]");
#Step("Pasirenkame juridinio asmens organizaciją iš reikšmių sąrašo")
public createOrganization selectMembership() {
button.click(naryste);
return this;
}
Selenium webdriver can't find this xpath:
Find element :By.xpath: //*[contains(#class,'v-label v-label--active theme--light primary--text') and contains(text(),'Narystė')]
P.S. the same problem if i choose other elements
AND this (selenium can't find)
To locate the element you can use the following Locator Strategy:
Using xpath:
By.xpath("//label[starts-with(#for,'input') and contains(.,'Narystė')]");
PS: Do add some waits before invoking the click()
I'm trying to automate adding requirements to a TestLink database. I'm running into an issue trying to click on this anchor/span.
<a hidefocus="on" class="x-tree-node-anchor" href="javascript:REQ_SPEC_MGMT(17473)" tabindex="1">
<span unselectable="on" id="extdd-6">0:Project-0 (0)</span>
</a>
Here is the section of Python code with things I've tried:
anchor = browser.find_element_by_xpath('//a[contains(#href, "REQ_SPEC_MGMT")]')
span = anchor.find_element_by_xpath('.//span')
anchor.click() # Doesn't work
span.click() # Doesn't work
browser.execute_script("arguments[0].click();", anchor) # Doesn't work
browser.execute_script("arguments[0].click();", span) # Doesn't work
I don't get any errors, but I still don't get the page that appears when I manually click on the link. I verified that I'm finding the correct anchor/span by dumping out the properties so I know I have the correct elements. I've also tried long pauses just to make sure that the element is clickable before I try it. Any ideas on what I am doing wrong? Thanks!
Update - Here's a larger section of the HTML:
<div id="tree_div" style="overflow:auto; height:100%;border:1px solid #c3daf9;" class=" x-panel x-tree">
<div class="x-panel-bwrap" id="ext-gen12"><div class="x-panel-body x-panel-body-noheader" id="ext-gen13" style="overflow: auto;">
<ul class="x-tree-root-ct x-tree-arrows" id="ext-gen14">
<li class="x-tree-node"><div ext:tree-node-id="17472" class="x-tree-node-el x-unselectable x-tree-node-expanded" unselectable="on" id="extdd-1">
<span class="x-tree-node-indent"></span>
<img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-ec-icon x-tree-elbow-end-minus">
<img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-node-icon" unselectable="on" id="extdd-2">
<a hidefocus="on" class="x-tree-node-anchor" href="javascript:TPROJECT_REQ_SPEC_MGMT(17472)" tabindex="1">
<span unselectable="on" id="extdd-3">ProjTasks (0)</span>
</a>
</div>
<ul class="x-tree-node-ct" style="">
<li class="x-tree-node">
<div ext:tree-node-id="17473" class="x-tree-node-el x-unselectable folder x-tree-node-collapsed" unselectable="on" id="extdd-4">
<span class="x-tree-node-indent"><img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-icon"></span>
<img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-ec-icon x-tree-elbow-plus">
<img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-node-icon" unselectable="on" id="extdd-5">
<a hidefocus="on" class="x-tree-node-anchor" href="javascript:REQ_SPEC_MGMT(17473)" tabindex="1">
<span unselectable="on" id="extdd-6">0:Project-0 (0)</span></a></div><ul class="x-tree-node-ct" style="display:none;">
</ul>
</li>
At first, try to use implicit selenium wait, to make sure that all your elements is download.
anchor = WebDriverWait(browser,30).until(EC.element_to_be_clickable((By.XPATH, '//a[contains(#href, "REQ_SPEC_MGMT")]')))
span = WebDriverWait(anchor,30).until(EC.element_to_be_clickable((By.XPATH, './/span')))
If it does'n work fine, try to execut js script in href:
browser.execute_script("javascript:REQ_SPEC_MGMT(17473)")
or
browser.execute_script(anchor.get_attribute("href"))
I figured out the issue. Some of the characters I was passing to execute_script were being dropped by my vnc software (Python Selenium script drops keys but only when used on a VNC).
To click() on the element with text as 0:Project-0 (0) element is an JavaScript enabled element so to click() on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following solutions:
Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.x-tree-node-anchor[href*='REQ_SPEC_MGMT']>span[id^='extdd-']"))).click()
Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[#class='x-tree-node-anchor' and contains(#href, 'REQ_SPEC_MGMT')]/span[starts-with(#id, 'extdd-') and text()='0:Project-0 (0)']"))).click()
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
there is a pop up after adding item to cart but it does not pop sometimes
how can i have the loop, if there is pop up then click the close or continue button or just click the background to dismiss it.
if it does not pop then continue next step.
below is the element, it is pretty long. please help to check
<div class="a-popover-wrapper"><header class="a-popover-header"><h4 class="a-popover-header-content" id="a-popover-header-6">Add to Order</h4><button data-action="a-popover-close" class=" a-button-close a-declarative" aria-label="Close"><i class="a-icon a-icon-close"></i></button></header><div class="a-popover-inner" id="a-popover-content-6" style="height: auto; overflow-y: auto;">
<div id="abb-interstitial" class="a-section abb-interstitial">
<div id="abb-intl-product-view-B07KTYTTG9" class="a-section abb-intl-product-view" style="display: block;">
<!-- only true in interstitial popovers -->
<div class="a-row">
<div class="a-column a-span4 a-text-center abb-product-view-image-container">
<img src="https://images-na.ssl-images-amazon.com/images/I/31STSohmOiL._SL160_.jpg" class="a-image-wrapper a-manually-loaded abb-product-image" id="" alt="" data-a-image-source="https://images-na.ssl-images-amazon.com/images/I/31STSohmOiL._SL160_.jpg" data-a-hires="https://images-na.ssl-images-amazon.com/images/I/31STSohmOiL._SL500_.jpg">
</div>
<div class="a-column a-span8 a-span-last">
<h3 class="a-spacing-none">
<a class="a-link-normal abb-product-title" target="_blank" rel="noopener" href="/dp/B07KTYTTG9/ref=ods_dabb_B07KTYTTG9_productInfo">
AppleCare+ for 13-inch MacBook Pro (3 Years)
</a>
</h3>
<div class="a-section a-spacing-micro abb-product-merchant-container">
<span class="a-color-secondary">
from
<span class="abb-product-merchant">Amazon Digital Services LLC</span>
</span>
</div>
<div class="a-section a-spacing-micro abb-product-reviews">
<style type="text/css">
/*
* Fix for UDP-1061. Average customer reviews has a small extra line on hover
* https://omni-grok.amazon.com/xref/src/appgroup/websiteTemplates/retail/SoftlinesDetailPageAssets/udp-intl-lock/src/legacy.css?indexName=WebsiteTemplates#40
*/
.noUnderline a:hover {
text-decoration: none;
}
</style>
<div id="averageCustomerReviews" class="a-spacing-none" data-asin="B07KTYTTG9" data-ref="dpx_acr_pop_">
<span class="a-declarative" data-action="acrStarsLink-click-metrics" data-acrstarslink-click-metrics="{}">
<span id="acrPopover" class="reviewCountTextLinkedHistogram noUnderline" title="4.0 out of 5 stars">
<span class="a-declarative" data-action="a-popover" data-a-popover="{"max-width":"700","closeButton":"false","position":"triggerBottom","url":"/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?contextId=dpx&asin=B07KTYTTG9"}">
<a href="javascript:void(0)" class="a-popover-trigger a-declarative">
<i class="a-icon a-icon-star a-star-4"><span class="a-icon-alt">4.0 out of 5 stars</span></i>
<i class="a-icon a-icon-popover"></i></a>
</span>
<span class="a-letter-space"></span>
</span>
</span>
<span class="a-letter-space"></span>
<span class="a-declarative" data-action="acrLink-click-metrics" data-acrlink-click-metrics="{}">
<a id="acrCustomerReviewLink" class="a-link-normal" href="#customerReviews">
<span id="acrCustomerReviewText" class="a-size-base">2 customer reviews</span>
</a>
</span>
<script type="text/javascript">
P.when('A', 'ready').execute(function(A) {
A.declarative('acrLink-click-metrics', 'click', { "allowLinkDefault" : true }, function(event){
if(window.ue) {
ue.count("acrLinkClickCount", (ue.count("acrLinkClickCount") || 0) + 1);
}
});
});
</script>
<script type="text/javascript">
P.when('A', 'cf').execute(function(A) {
A.declarative('acrStarsLink-click-metrics', 'click', { "allowLinkDefault" : true }, function(event){
if(window.ue) {
ue.count("acrStarsLinkWithPopoverClickCount", (ue.count("acrStarsLinkWithPopoverClickCount") || 0) + 1);
}
});
});
</script>
</div>
</div>
<div class="a-section a-spacing-base abb-product-price">
<span class="a-size-medium a-color-secondary abb-product-list-price a-text-strike">
</span>
<span class="a-size-medium a-color-price abb-product-buying-price">
$269.00
</span>
</div>
<div class="a-section abb-product-feature-bullets">
<ul>
<li>AppleCare product must be purchased with an applicable Apple device. Terms & Conditions will be delivered via email post-enrollment and can be downloaded through your Digital Items Page (Your Account-->Games and Software).</li>
<li>AppleCare+ will automatically be enrolled at time of purchase, and Proof of Coverage will be emailed within 3 days after your device ships.</li>
<li>AppleCare+ for Mac extends your coverage to three years from your AppleCare+ purchase date and adds up to two incidents of accidental damage coverage</li>
<li>Each incident of accidental damage coverage is subject to a service fee of $99 for screen damage or external enclosure damage, or $299 for other damage, plus applicable tax</li>
<li>Get 24/7 priority access to Apple experts by chat or phone</li>
<li>Onsite repair for desktop computers: Request that a technician come to your work site</li>
<li>Mail-in repair for portable computers: Mail in your Mac using a prepaid shipping box provided by Apple</li>
<li>Carry-in repair: Take your Mac to an Apple Store or other Apple Authorized Service Provider</li>
<li>Hardware coverage for your Mac computer, battery, included accessories such as the power adapter, Apple memory (RAM), AirPort, and Apple USB SuperDrive</li>
<li>Software support for using macOS and iCloud, quick how-to questions about Apple-branded apps, such as Photos, iMovie, GarageBand, Pages, Numbers, Keynote, and more, connecting to printers and AirPort networks</li>
</ul>
</div>
</div>
</div>
<div class="a-row">
<div class="a-column a-span8 a-push4">
<div class="a-section a-spacing-mini a-spacing-top-base abb-intl-product-cta">
<div class="a-row a-spacing-top-base">
<div data-asin="B07KTYTTG9" class="a-checkbox abb-intl-product-ato"><label><input type="checkbox" name="" value="" autocomplete="off"><i class="a-icon a-icon-checkbox"></i><span class="a-label a-checkbox-label">
<span class="a-text-bold">Add AppleCare+ for 13-inch MacBook Pro (3 Years) to your order</span>
</span></label></div>
</div>
</div>
</div>
</div>
</div>
<div id="abb-intl-pop-cta" class="a-section a-spacing-base">
<div class="a-row">
<div class="a-column a-span8 a-push4">
<span class="a-button a-button-primary abb-intl-ato abb-intl-continue" id="a-autoid-13"><span class="a-button-inner"><input class="a-button-input" type="submit" aria-labelledby="a-autoid-13-announce"><span class="a-button-text a-text-center" aria-hidden="true" id="a-autoid-13-announce">
Continue
</span></span></span>
<span class="a-button a-button-base abb-intl-decline aok-hidden" id="a-autoid-14"><span class="a-button-inner"><input class="a-button-input" type="submit" aria-labelledby="a-autoid-14-announce"><span class="a-button-text a-text-center" aria-hidden="true" id="a-autoid-14-announce">
No thanks
</span></span></span>
</div>
</div>
</div>
</div>
</div></div>
Try the following code.Hope this will work.
To click on continue try this
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.Xpath("//span[normalize-space(.)='Continue']/parent::span/input[#class='a-button-input']"));
Actions action = new Actions(driver);
action.moveToElement(element).click().build().perform();
}
OR
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.Xpath("//span[normalize-space(.)='Continue']/parent::span/input[#class='a-button-input']"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();",element);
}
//To click on No Thanks try this
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.Xpath("//span[normalize-space(.)='No thanks']/parent::span/input[#class='a-button-input']"));
Actions action = new Actions(driver);
action.moveToElement(element).click().build().perform();
}
OR
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.Xpath("//span[normalize-space(.)='No thanks']/parent::span/input[#class='a-button-input']"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();",element);
}
//To close the popup
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.cssSelector("i.a-icon.a-icon-close"));
Actions action = new Actions(driver);
action.moveToElement(element).click().build().perform();
}
OR
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.cssSelector("i.a-icon.a-icon-close"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();",element);
}
Here is the logic.
// change the action based on scenario
String action = 'Continue';
if (driver.findElements(By.Xpath("//div[#class='a-popover-wrapper']")).size()>0){
driver.findElement(By.Xpath("//div[#class='a-popover-wrapper']//span[#class='a-button-text a-text-center' and normalize-space(.)='" + action + "']")).click();
}
I am using python:
def escape_pop(driver):
try:
if len(str(driver.find_element_by_class_name("a-popover-wrapper"))) > 0: # check if popup is present
actions = ActionChains(driver)
actions.send_keys(Keys.ESCAPE).perform()
except:
pass
after trying many methods.
below is working.
i add a wait element
then add one more click.
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("a-autoid-13")));
driver.findElement(By.cssSelector("i.a-icon.a-icon-close")).click();
I want to automate the file uploading process which is using a file upload control built in bootstrap.
I am doing the same using webdriver.
Below is my code, but unfortunately it is not working:
element=driver.findElement(By.xpath("//[#id='upload']/fieldset/div[2]/input[1]"));
element.sendKeys(pathToFile);
It is giving an element not visible error.
Here is the example of the bootstrap fileupload control which I am trying to automate-
Via JavaScript:
on this URL http://markusslima.github.io/bootstrap-filestyle/
Please see below style-
$(":file").filestyle({icon: false});
Ok. i think i solved it.
WebElement fileInput = driver.findElement(By.id("document"));
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("document"));
js.executeScript("arguments[0].setAttribute('style', 'left:30px')",
element);
fileInput.sendKeys(fileName);
the bootstrap-filestyle.js hide a input element so you have to move it to the visible area and then set it in the standard way.
so much trouble for such a simple solution.
Here is my original html code:
<span id="documentUpload">
<input type="file" id="document" name="document" class="notMandatory" onkeypress="return noenter(event)" tabindex="-1" style="position: absolute; left: -9999px;">
<div class="bootstrap-filestyle" style="display: inline;" tabindex="0">
<input type="text" class="input-xlarge" disabled="" autocomplete="off">
<label for="document" class="btn"><i class="icon-folder-open"></i> <span>Upload</span></label>
</div>
</span>
I am not able to click on the below HTML values through selenium webdriver click command through Java.
Here's my HTML...I have to click on PAAcctAcctRels, PAAcctActivityData, etc. as in the HTML.
I tried with LinkText (driver.findElement(By.linkText("PAAcctAcctRels")).click();) and xpath (driver.findElement(By.xpath(".//[#id='primaryNavLevel2Z6_G868H4S0K881F0AAEO37LG28N0']/div[1]/a")).click();)
<div id="primaryNavLevel2Z6_0G5A11K0KGF200AIUB98T20G52" class="dropdown_1columns">
<div class="col_1">
<a class="" href="?uri=nm:oid:Z6_0G5A11K0KGF200AIUB98T20G53">
<strong>
<span lang="en" dir="ltr">
PAAcctAcctRels
<span class="wpthemeAccess"> currently selected</span>
</span>
</strong>
</a>
</div>
<div class="col_1">
<a class="" href="?uri=nm:oid:Z6_0G5A11K0KGF200AIUB98T20GD4">
<span lang="en" dir="ltr">PAAcctActivityData</span>
</a>
</div>
<div class="col_1">
<a class="" href="?uri=nm:oid:Z6_0G5A11K0KGF200AIUB98T20GT1">
<span lang="en" dir="ltr">PAAcctAddrEmail</span>
</a>
</div>
Is there any other way to do this..please let me know.
1- For Clicking on text 'PAAcctActivityData', you can use the below code:
driver.findElement(By.xpath("//span[.='PAAcctActivityData']")).click();
2- For Clicking on text 'PAAcctAddrEmail', you can use the below code:
driver.findElement(By.xpath("//span[.='PAAcctAddrEmail']")).click();
NOTE:- The above xpaths will locate thespan elements with exact innerHTML/text as 'PAAcctActivityData' or 'PAAcctAddrEmail', respectively.
By.linkText("PAAcctAcctRels") won't work because that link has more text (ie ' currently selected'), and the problem with your xpath is that is starts with .//
The following should work (I have avoided using * for performance)
By.xpath("//div[#id='primaryNavLevel2Z6_G868H4S0K881F0AAEO37LG28N0']/div[1]/a")
Try using //[#id='primaryNavLevel2Z6_G868H4S0K881F0AAEO37LG28N0']/div[1]/a/span
as xpath. Remove the initial '.' and add '/span' at the end.