How to write XPATH for nodes under dynamic hierarchy - xpath

I got a big XML. A snippet of that XML look like this:
<div class="x-column-inner" id="ext-gen422" style="width: 850px;">
<div id="ext-comp-1206" style="width: 14px;" class=" x-column">
<div tabindex="-1" class="x-form-item x-hide-label" id="ext-gen434">
<label class="x-form-item-label" style="width:100px;" for="ext-comp-1180" id="ext-gen435"></label>
<div style="padding-left:105px" id="x-form-el-ext-comp-1180" class="x-form-element">
<div class="x-form-check-wrap" id="ext-gen436" style="width: 14px; height: 28px;">
<input type="checkbox" name="ext-comp-1180" id="ext-comp-1180" autocomplete="off" class=" x-form-checkbox x-form-field">
<label class="x-form-cb-label" for="ext-comp-1180" id="ext-gen437"> </label>
</div></div> <div class="x-form-clear-left">
</div>
</div>
</div>
<div id="ext-comp-1207" style="width: 150px;" class=" x-column">
<label id="ext-comp-1203" style="width: 140px;">Add to Watchlist</label>
</div>
<div id="ext-comp-1208" style="width: 107px;" class=" x-column">
I need to find 'input' node of checkbox type based on label node having text 'Add to Watchlist'.
As both 'input' and 'label' node lies in different hierarchy, // syntax doesn't seem to work:
//div[label[contains(text(),'Add to Watchlist')]]
will just give parent div of child label.
I tried to start from the topmost node of this snippet
$x("//div[#class='x-column-inner' and //label[contains(text(),'Add to Watchlist')]]")
but that is giving 6 possible matches.
Note: #id attribute can't be used as this is getting assigned dynamically to nodes so next time page loads #id will be different.
I don't want to use position() predicate as that makes XPATH static and xpath may break with any change in position.

You could try something like this, but it looks very greedy... Basically what it does is searching in every axes of the input tags to see if there is an associated label tag. So for each input it searches in its ancestors, descendants and siblings.
There are certainly some smarter solutions.
//input[#type = 'checkbox' and (#id = ancestor::label/#for or #id = descendant::label/#for or #id = following::label/#for or #id = preceding::label/#for)]
However your snippet is not interesting no input tag will be matched, please consider providing a better snippet. It would improve the answers accuracy.
Edit : Here is a (non-tested) way to add the 'Add to Watchlist' constraint.
//input[#type = 'checkbox' and (#id = ancestor::label[. = 'Add to Watchlist']/#for or #id = descendant::label[. = 'Add to Watchlist']/#for or #id = following::label[. = 'Add to Watchlist']/#for or #id = preceding::label[. = 'Add to Watchlist']/#for)]
But once again, those xpath requests are very greedy and your are not guaranteed to match every input element associated to a label for example the following input won't be match in this snippet:
<div>
<div>
<label for="id">Add to Watchlist</label>
</div>
<div>
<input type="checkbox" id="id" />
</div>
<div>
There may be more efficient solutions in one xpath request, but you should consider doing several request.
For example, one request to find every for attribute value of the label elements with the text 'Add to Watchlist' and then doing another request to find the associated input elements.
I should also try to restrict your request to the scope a the underlying form element. Perhaps I will edit with a better request if I find the time.
Edit 2
Here is a working and smarter request
//form//input[#type = 'checkbox' and #id = ancestor::form[1]//label[. = 'Add to Watchlist']/#for]
You can confront it to this snippet
<html>
<form>
<label for="bar">Add to Watchlist</label>
<div>
<div>
<label for="id">Add to Watchlist</label>
</div>
<div>
<input type="checkbox" id="id" />
<input type="checkbox" id="foo" />
<input type="checkbox" id="bar" />
<input type="checkbox" />
<input type="checkbox" id="" />
</div>
</div>
</form>
<label for="foo">Add to Watchlist</label>
</html>
Bust the most important is that you understand how it works and why it is better. Please take the time to think about it.

Related

Playwright + CodeceptJS - Unable to find element by Xpath

In my code I can usually find an element by Xpath and perform actions like shown below
await I.fillField('//*[#id="edit-name"]','user1');
I am seeing the following error when I perform the following action. As the ID is dynamically created. Is there a recommended approach to tackle this type of elements?
await I.fillField('//*[#id="crmUiId_1"]','SomeTextHere');
Error:
**TypeError: Cannot read property '$$' of null
at findElements (node_modules/codeceptjs/lib/helper/Playwright.js:2087:18)
at Playwright._locate (node_modules/codeceptjs/lib/helper/Playwright.js:822:12)**
Associated HTML:
<div crm-ui-field="{name: 'caseTypeDetailForm.title', title: ts('Title')}" class="ng-isolate-scope crm-section"><div class="label">
<label crm-ui-for="caseTypeDetailForm.title" crm-depth="1" crm-ui-force-required="" for="crmUiId_1"><span ng-class="cssClasses"><span ng-transclude=""><span class="ng-binding ng-scope">Title</span></span><span crm-ui-visible="crmIsRequired" class="crm-marker ng-isolate-scope" title="This field is required." style="visibility: inherit;">*</span></span></label>
<!-- ngIf: help -->
</div>
<div class="content" ng-transclude="">
<input crm-ui-id="caseTypeDetailForm.title" type="text" name="title" ng-model="caseType.title" class="big crm-form-text ng-pristine ng-scope ng-empty ng-invalid ng-invalid-required ng-touched" required="" id="crmUiId_1">
</div>
<div class="clear"></div>
</div>
The issue here is actually the ID "crmUiId_1" is dynamically generated. Instead I tried xpath with ng-model="caseType.title" but it doesn't seem to be working either.
I would just make sure you wait for it:
await page.waitForSelector('#crmUiId_1')
await page.fill('#crmUiId_1', 'whatever')
Otherwise the page might still be loading.

Python/Plone: Getting all keywords and showing for EDIT content is very slow

Python/Plone: Getting all keywords and showing for EDIT content is very slow (keywords.pt)
No of keywords is 20000 so traversing these huge no of keywords is taking one minute.
Keywords which no has grown large is taking time....any solution is welcomed
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal"
xmlns:metal="http://xml.zope.org/namespaces/metal"
xmlns:i18n="http://xml.zope.org/namespaces/i18n"
i18n:domain="plone">
<head><title></title></head>
<body>
<!-- Keyword Widgets -->
<metal:view_macro define-macro="view"
tal:define="kssClassesView context/##kss_field_decorator_view;
getKssClasses nocall:kssClassesView/getKssClassesInlineEditable;">
<div metal:define-macro="keyword-field-view"
tal:define="kss_class python:getKssClasses(fieldName,
templateId='widgets/keyword', macro='keyword-field-view');
uid context/UID|nothing"
tal:attributes="class kss_class;
id string:parent-fieldname-$fieldName-$uid">
<ul metal:define-slot="inside">
<li tal:repeat="item accessor"
tal:content="item"/>
</ul>
</div>
</metal:view_macro>
<metal:define define-macro="edit">
<metal:use use-macro="field_macro | context/widgets/field/macros/edit">
<tal:define metal:fill-slot="widget_body" define="contentKeywords accessor;
allowedKeywords python: context.collectKeywords(fieldName, field.accessor, widget.vocab_source);
site_props context/portal_properties/site_properties|nothing;
format widget/format | string:select;
allowRolesToAddKeywords site_props/allowRolesToAddKeywords|nothing;">
<div tal:condition="allowedKeywords" id="existingTagsSection">
<tal:comment tal:replace="nothing">
dl semantically associates selector name with values
</tal:comment>
<dl id="existingTags">
<label for="subject">
<dt id="existingTagsTitle">uuuuuuuuuuuuuuuuuuuuuuuuu
<span i18n:translate="label_select_existing_tags">
Select from existing tags.
</span>
</dt>
<span id="existingTagsHelp" class="formHelp" i18n:translate="label_existingTagsHelp">
Use Control/Command/Shift keys to select multiple tags.
</span>
<tal:comment tal:replace="nothing">
Type-to-skip functionality with javascript enabled
could be described as
"Hover and type the first letter to skip through tags."
However, on touch-driven devices, vertical hover typically
scrolls the page, so horizontal hover is necessary to enable this.
Alternatively, clicking any of the tags also enables type-to-skip.
So the help could technically be extended to handle this special case
as "Hover or click and type the first letter to skip through tags.",
but I think this would be confusing to the majority of users.
The decision at this point is to not try to explain any of this on the page.
</tal:comment>
</label>
<div class="visualClear"><!-- --></div>
<select id="predefined_subjects"
name="predefined_subjects:list"
size="14"
multiple="multiple"
tal:condition="python:format!='checkbox'"
tal:attributes="id string:${fieldName};
name string:${fieldName}_existing_keywords:list;">
<option value="#" tal:repeat="keyword allowedKeywords"
tal:content="keyword" tal:attributes="value keyword;
selected python:test(context.unicodeTestIn(keyword, value), 'selected', None)">
An existing tag
</option>
</select>
<tal:comment tal:replace="nothing">
These spans are hidden by css, and used by the JavaScript called below.
</tal:comment>
<span id="noTagsSelected" i18n:translate="label_noTagsSelected">No tags currently selected.</span>
<span id="oneOrMoreTagsSelected" i18n:translate="label_oneOrMoreTagsSelected">% tags currently selected.</span>
<tal:comment tal:replace="nothing">
Call js to modify this widget with both a scrollbar and checkboxes.
There may be a better place to put this js call;
examples exist in others' widget.py and js files,
but having it here covers cases where some but not all select elements
call js to be modified.
Todo: The #subject should eventually refer to the template variable.
</tal:comment>
<script type="text/javascript">
jq(document).ready( function() {
jq("#subject").multiSelect();
});
</script>
<input type="hidden"
value=""
tal:condition="not:field/required | nothing"
tal:attributes="name string:${fieldName}_existing_keywords:default:list" />
<tal:loop tal:repeat="keyword allowedKeywords"
tal:condition="python:format=='checkbox'">
<div class="ArchetypesKeywordValue" id=""
tal:attributes="id string:archetypes-value-${fieldName}_${repeat/keyword/number}">
<input class="blurrable"
tal:attributes="
type string:checkbox;
name string:${fieldName}_existing_keywords:list;
id string:${fieldName}_${repeat/keyword/number};
checked python:test(context.unicodeTestIn(keyword, value), 'checked', None);
value keyword" />
<label
tal:content="keyword"
tal:attributes="for string:${fieldName}_${repeat/keyword/number}">
An existing tag
</label>
</div>
</tal:loop>
</dl>
<dl id="selectedTagsSection">
<dt id="selectedTagsHeading" class="formHelp"></dt>
<dd id="selectedTags"></dd>
</dl>
<div class="visualClear"><!-- --></div>
</div>
<!-- <tal:condition condition="python:not widget.roleBasedAdd or (allowRolesToAddKeywords and [role for role in user.getRolesInContext(context) if role in allowRolesToAddKeywords])">-->
<dl id="newTagsSection">
<label for="subject_keywords">
<dt id="newTagsTitle">
<span i18n:translate="label_create_new_tags">
Create and apply new tags.
</span>
</dt>
<span id="newTagsHelp" i18n:translate="label_newTagsHelp" class="formHelp">
Enter one tag per line, multiple words allowed.
</span>
</label>
<br />
<dd id="newTags">
<textarea
id="entered_subjects"
name="subject:lines"
rows="4"
tal:attributes="id string:${fieldName}_keywords;
name string:${fieldName}_keywords:lines;"
tal:define="subject python:[item for item in value if not context.unicodeTestIn(item,allowedKeywords)]"
tal:content="python:'\n'.join(subject)">
A new tag
</textarea>
</dd>
</dl>
<!-- </tal:condition>-->
</tal:define>
</metal:use>
</metal:define>
<div metal:define-macro="search">
<div metal:use-macro="context/widgets/keyword/macros/edit">
</div>
</div>
</body>
</html>
I fear is a know issue of the old Plone 4 keyword widget.
You should probably change the widget.
An add-on like eea.tags should help.
You can also try to use Plone 5 widget from plone.app.widgets, but this probably it's a more complex task (and not without side effects).

Selenium script for dynamic ID textbox

I have to click on element whose Id is changeable,means dynamic value assign to text box everytime . I have to insert value in text box.
Following is the inspect element code of text box
<div class="invoicing-details">
<div>
<label for="PaidToName_b62b89226e5f4fcbb74d0d27a9db88ca"> To </label>
<input id="PaidToContactID" type="hidden" value="" name="PaidToContactID">
<div class="controls">
<input id="PaidToName_b62b89226e5f4fcbb74d0d27a9db88ca" type="hidden" style="display:none;" value="" name="PaidToName_b62b89226e5f4fcbb74d0d27a9db88ca">
<input id="PaidToName_b62b89226e5f4fcbb74d0d27a9db88ca_value" class=" autocompleter field " type="text" style="width:127px;" tabindex="10" value="" maxlength="255" name="PaidToName_b62b89226e5f4fcbb74d0d27a9db88ca_value" autocomplete="off">
<div id="PaidToName_b62b89226e5f4fcbb74d0d27a9db88ca_suggestions" class="autocomplete" style="display: none; height: 200px; width: 200px;"> </div>
<script type="text/javascript">
</div>
</div>
"PaidToName_b62b89226e5f4fcbb74d0d27a9db88ca_value" this is text box id.
I used following code
self.set_text_value('div.invoicing-details input' ,"my value",true)
but it does not work and getting syntax error.
Can anyone help me and provide syntax how to write ruby script for seleinum.
Dynamic ids very bad for automation. You can try to add other property to input element with stable name. As i clearly understood you need to click on element and then input text in it?! I'm not good at ruby, but i think this should look like:
element = driver.find_elements(:css,".invoicing-details .autocompleter")
element.click
element.send_keys "Some text"
You can try to find id of an element using next xpath: //input[#id=(//label[contains(text(),'To')]/#for)]. Here you find a label by its text and then get for attribute (it is needed id).
element = driver.find_elements(:xpath,"//input[#id=(//label[contains(text(),'To')]/#for)]")
element.click
element.send_keys "Some text"

Magento - newsletter pop code using ajax update in form

I have the below code that is being used in cms page pop up
the problem im having is if you leave email address input field blank and hit the submit (in the case "Get Code" button, you briefly see the red validation message but then hides the form, shows the hidden div.
why or how can I prevent this process, i want it to validate but proceed to show the hidden div content. Below is the code.
<div id="pop-confirm" style="display: none;">
<h1 style="color: #000000; font-weight: bold;">THANKS!</h1>
<p> </p>
<h2>Use code: <strong>extra15</strong><br /> for 15% off your purchase.</h2>
</div>
<form id="newsletter-validate-detail" action="home/send" method="post" onSubmit="new Ajax.Updater({success:'newsletter-validate-detail'}, 'newsletter/subscriber/new', {asynchronous:true, evalScripts:false, onComplete:function(request, json){Element.hide('newsletter-validate-detail');Element.show('pop-confirm');}, onLoading:function(request, json){}, parameters:Form.serialize(this)}); return false;">
<div class="block-content">
<h2>ENTER YOUR EMAIL<br /> AND GET</h2>
<div class="form-subscribe-header">
<h1>15% OFF</h1>
<br />
<h1>EVERYTHING!</h1>
</div>
<div class="input-box"><input id="newsletter" class="input-text required-entry validate-email" title="Sign up for our newsletter" type="text" name="email" /></div>
<br />
<div class="actions"><button class="button" title="Get Code" type="submit"><span><span>Get Code</span></span></button></div>
<br />
<p><em>* Promotion ends April 6th</em></p>
</div>
</form>
<script type="text/javascript">// <![CDATA[
var newsletterSubscriberFormDetail = new VarienForm('newsletter-validate-detail');
// ]]></script>
Im very new to ajax so maybe ive done something wrong.
any ideas or suggestion would be greatly appreciated.
Thanks
Try changing your onSubmit to the following:
onSubmit="if(newsletterSubscriberFormDetail.validator.validate()){ new Ajax.Updater({success:'newsletter-validate-detail'}, 'newsletter/subscriber/new', {asynchronous:true, evalScripts:false, onComplete:function(request, json){Element.hide('newsletter-validate-detail');Element.show('pop-confirm');}, onLoading:function(request, json){}, parameters:Form.serialize(this)}); } return false;"`
This wil trigger the validator before submitting the form with AJAX. Works perfect for me :)

input fields not showing in hide/show div with radio buttons

I have a very basic hide/show div function set up for when people click a certain radio button. In one of the hidden divs I need to create a form however when I add input fields to the hidden div my function stops working.
<div id="tabs">
<div id="nav">
<input type="radio" name="primary_contact_director" value="Yes" class="div1">Yes</input>
<input type="radio" name="primary_contact_director" value="No" class="div2">No</input>
</div>
<div id="div1" class="tab">
<p>this is div 1</p>
</div>
<div id="div2" class="tab">
<p>this is div 2</p>
</div>
</div>
<script type="text/javascript" charset="utf-8">
(function(){
var tabs =document.getElementById('tabs');
var nav = tabs.getElementsByTagName('input');
/*
* Hide all tabs
*/
function hideTabs(){
var tab = tabs.getElementsByTagName('div');
for(var i=0;i<=nav.length;i++){
if(tab[i].className == 'tab'){
tab[i].className = tab[i].className + ' hide';
}
}
}
/*
* Show the clicked tab
*/
function showTab(tab){
document.getElementById(tab).className = 'tab'
}
hideTabs(); /* hide tabs on load */
/*
* Add click events
*/
for(var i=0;i<nav.length;i++){
nav[i].onclick = function(){
hideTabs();
showTab(this.className);
}
}
})();
This code works however when I add
<label class="title">First Name:</label>
<input type="text" name="first_name" class="form">
<label class="title">Last Name:</label>
<input type="text" name="last_name" class="form">
<label class="title">Business Address:</label>
<span class="instructions">Please enter a physical address. P.O. Boxes are not acceptable for filing.<br>
If your business is run out of your home, please list that address.</span><br>
<input type="text" name="business_address" class="form">
<label class="title">City:</label>
<input type="text" name="business_city" class="form">
<label class="title">State</label>
<select name="business_state">
<option value="California">California</option>
</select>
<label class="title">Zip Code:</label>
<input type="text" name="business_zip" class="form">
<label class="title">Business Phone Number:</label>
<input type="text" name="business_phone" class="form"><br>
to my div2 it stops working.
Hopefully this is a clear explanation. Any help is always appreciated!
In your hideTabs() function, you've got two typos.
First, you're iterating through the tab[] array, but you're checking it against the length of the nav[] array. This works because you have the same number of elements in your first example, but that's just a coincidence. If you evaluate it against the tab[] array's length, it will work better. The other problem you have is that your for loop ends at greater-than-or-equal-to length. THe problem is that arrays start counting at zero, so if the length is 3, the items on the list are tab[0], tab[1], and tab[2]. your code was trying to set something for tab[3], which didn't exist.
Here's the working code:
/*
* Hide all tabs
*/
function hideTabs(){
var tab = tabs.getElementsByTagName('div');
for(var i=0;i<tab.length;i++){
if(tab[i].className == 'tab'){
tab[i].className = tab[i].className + ' hide';
}
}
}
In the future, you should look into using the javascript console in Chrome (or any other browser) to check for errors if your scripts stop working—usually there's an error that that will give you hints as to what's happening.

Resources