How to get all direct child elements of current element via CSS Selectors? - selenium

I'd like to get all child elements of some specific element with Selenium. Let's say I have the following HTML:
<html>
<table>
<tr>
<td>Test 1</td>
<td id="123">Test <b>2</b>
<span>span_text</span>
</td>
<td>Test 3</td>
</tr>
</table>
</html>
First, I'd like to find the second td element by its id and then I'd like to find all of its child elements (i.e. the b and span elements). Finding the second td element isn't hard:
from selenium import webdriver
from selenium.webdriver.common.by import By
page_source = """<table>
<tr>
<td>Test 1</td>
<td id="123">Test<b>2</b><span>span_text</span></td>
<td>Test 3</td>
</tr>
</table>
"""
driver = webdriver.Chrome()
driver.execute_script('document.documentElement.innerHTML=arguments[0]', f"<html>{page_source}</html>")
element = driver.find_element(By.ID, "123")
In order to find the child elements, I tried the td > * CSS Selector:
for elements in element.find_elements(By.CSS_SELECTOR, f"td > *"):
print(element.tag_name)
However, this prints two td tags instead of b and span. I also tried the . > * CSS Selector instead, which seems to be invalid. How I can select all (direct) child elements of an WebElement in Selenium by CSS Selectors?
Note: I want to use the element.find_elements() method, i.e. I want selenium to only search within the already found element.

You were almost there. Your code is perfect. You just need to keep a track that within for statement in each iteration the decendants are referred as elements. So you have to invoke:
print(elements.tag_name) # instead of element, it should be elements
Here is the complete program:
page_source = """<table>
<tr>
<td>Test 1</td>
<td id="123">Test<b>2</b><span>span_text</span></td>
<td>Test 3</td>
</tr>
</table>
"""
driver = webdriver.Chrome(service=s, options=options)
driver.execute_script('document.documentElement.innerHTML=arguments[0]', f"<html>{page_source}</html>")
element = driver.find_element(By.ID, "123")
for elements in element.find_elements(By.CSS_SELECTOR, f"td > *"):
print(elements.tag_name)
Output:
b
span

There's a bug in your code :)
for elements in element.find_elements(By.CSS_SELECTOR, f"td > *"):
print(element.tag_name)
^ elements
This should be elements.tag_name (plural of element) to use the loop variable, elements. Your variable on the previous line is element so you were printing the TD from the previous line twice.
Having said that, you can do this in a single step and simplify your code and save a little time
for element in driver.find_elements(By.CSS_SELECTOR, "[id='123'] > *"):
print(element.tag_name)

Related

How to find element using xpath when dom changes with window size

The DOM my test application changes depending upon the window size. So I am trying to write an XPATH which will cater for both of these scenarios.
Scenario 1: When the window is maximum size below is the dom:
<tbody>
<tr><td class="sv-table-col-xs"><img src="image.gif">
</td>
<td>03/Mar/2020</td>
<td><span class="sv-label sv-label-primary">You</span>
</td><td>0% of 1</td>
<td>Complete academic review</td>
</tr>
</tbody>
I am using xpath:
//tr[td[contains(text(), '03/Mar/2020')]]//a[text()='Complete academic review']
This works fine and finds the element.
Scenario 2: Below is the DOM when window is shrinked
<tbody>
<tr><td class="sv-table-col-xs">
<b class="tablesaw-cell-label">Status</b>
<span class="tablesaw-cell-content"><img src="../images/emailunr.jpg" style="border:0px" alt="..\images\icons\exploding_email1.gif.gif"></span>
</td>
<td><b class="tablesaw-cell-label">Due Date</b>
<span class="tablesaw-cell-content">03/Mar/2020</span>
</td>
<td><b class="tablesaw-cell-label">Primary Reviewer</b>
<span class="tablesaw-cell-content"><span class="sv-label sv-label-primary">You</span></span>
</td>
<td class="tablesaw-cell-hidden"><b class="tablesaw-cell-label">Other Reviewers</b>
<span class="tablesaw-cell-content">0% of 1</span>
</td>
<td class="tablesaw-cell-hidden"><b class="tablesaw-cell-label">Action</b><span class="tablesaw-cell-content">
Complete academic review
</span></td></tr>
</tbody>
For this the xpath changes to:
//tr/td[5]/span/a
to get to both elements I have tried to use:
//tr/td[5]/span/a | //tr[td[contains(text(), '03/Mar/2020')]]//a[text()='Complete academic review']
this xpath works but I on shrinked window I am not validating the element with text contains ''03/Mar/2020' & 'Complete academic review'.
Not sure if there is a way to validate the texts in both scenarios before selecting the element.
You want to use string value of a node. And function text() doesn't do it.
So instead use . or string() at least for date filtering part.
//tr[td[contains(., '03/Mar/2020')]]//a[text()='Complete academic review']

How to extract the text 8 from the 2nd row and 2nd column as per the html through Selenium and VBA

Using selenium vba i want 2nd row and 2nd column value from webpage table below is the code which i have try but it capture all table.
The output which i want is 8.
driver.FindElementByXPath("//table[contains(#class,'zedoLocTable')]").text
Please find the below html code.
<tr>
<td colspan="4">
<div id="localityTiers">
<br><br>
<table class="zedoLocTable" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<th>TYPE</th>
<th>TIER</th></tr>
<tr>
<td><b>Resedential Sale</b>
</td><td>8</td>
</tr>
<tr><td><b>Resedential Rent</b>
</td><td>5</td>
</tr><tr>
<td><b>Commercial Sale</b>
</td><td>1</td>
</tr><tr>
<td><b>Commercial Lease</b>
</td><td>1</td>
</tr></tbody></table><table></table></div>
</td>
</tr>
Below is the table pic
As per the HTML you have shared to extract the text 8 you can use the following solution:
driver.FindElementByXPath("//table[#class='zedoLocTable']//tr/td/b[contains(.,'Resedential Sale')]//following::td[1]").text
You can use a faster CSS selector, than using xPath, if you are working with later IE or other browers apart from IE
Debug.Print driver.FindElementByCSS(".zedoLocTable td + td").innerText

Copy text from website using Selenium for python

I'm trying to copy text from a website with the following code and I want it to automatically click the "NEXT" button at the end of the table, without clicking it the code works just fine but when I add the last line to click it gives the error:
"Message: Element is no longer attached to the DOM Stacktrace: at
fxdriver.cache.getElementAt
(resource://fxdriver/modules/web-element-cache.js:9354)
at Utils.getElementAt (file:///c:/users/user/appdata/local/temp/tmpa7dvts/extensions/fxdriver#googlecode.com/components/command-processor.js:8978)
at WebElement.getElementText (file:///c:/users/user/appdata/local/temp/tmpa7dvts/extensions/fxdriver#googlecode.com/components/command-processor.js:11965)
at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/user/appdata/local/temp/tmpa7dvts/extensions/fxdriver#googlecode.com/components/command-processor.js:12534)
at DelayedCommand.prototype.executeInternal_ (file:///c:/users/user/appdata/local/temp/tmpa7dvts/extensions/fxdriver#googlecode.com/components/command-processor.js:12539)
at DelayedCommand.prototype.execute/< (file:///c:/users/user/appdata/local/temp/tmpa7dvts/extensions/fxdriver#googlecode.com/components/command-processor.js:12481)"
The code I'm using is:
driver = webdriver.Firefox()
driver.get("https://it.website.com/Statistics")
wait = ui.WebDriverWait(driver, 10)
wait.until(page_is_loaded)
Next_first = 0
Next_first = driver.find_elements_by_id("next")[0]
data_vector [i]=driver.find_elements_by_class_name("tn")[i].text
Next_first.click()
While the website code is:
<tr>
<td class="tn"> text
</td>
<table class="table class" id="table id">
<thead>...code for table title...
</thead>
<tbody>
<tr>
<td class="tn">data
</td>
</tr>
</tbody>
<dd>
<a class="option clickable" id="next" data-page="1">NEXT</a>
</dd>
</tr>
Is there more than the html-source, like javascript?
Because the input could be detached by javascript, which means you have to wait for it to load properly ( driver.implicitly_wait(#seconds) )
here the link to the discription of "implicit-waits"
The second solution could be that you have to clear the cache/cookies of the webdriver before testing, which is described here

how to get Table element from a Div that has a Heading tag with a known text - using selenium and java

<h3>Movers and Shakers</h3>
<p>
<strong>Strategy Hint 1:</strong><br>
<strong>Strategy Hint 2:</strong><br>
</p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td> </td>
<td>ExternalId</td>
<td>Name</td>
<td>Price cents</td>
<td>Brand</td>
<tr>
<tr>
<td>1</td>
<td>123</td>
<td>Draw</td>
<td>2</td>
<td>Ciko</td>
<tr>
Now, the know text in the h3 tag is 'Movers and Shakers'. The table and h3 are in a Div tag. Now, how do I get the table for this specific div that has that specific known text('Movers and Shakers').
With the help of xpath, use following code to return the DIV element that contains a heading H3 with the text Movers and Shakers:
WebElement div = driver.findElement(By.xpath("//div[h3[text()='Movers and Shakers']]"));
Ant then, find the table inside this div web-element:
WebElement table = div.findElement(By.xpath(".//table"));
This will return the table element you want:
WebElement table = driver.findElement(By.xpath("//div[h3[contains(.,'Movers and Shakers')]]")).findElement(By.tagName("table"));
this short line worked
WebElement table = driver.findElement(By.xpath("//h3[contains(text(),'Movers and Shakers')]/following-sibling::table"));

Selenium link for image list based on image name or link name

I have a menu ribbon that is constructed from tags, Sub lists are hidden until the upper level list is clicked on. How do I identify the target of this image so that I can click on it?
<li class="rbnsel">
<div class="rbl" href="option/index?lfeCyc=Active">
<img src="../icn/op.png">
</img>
Options
</div>
Selenium IDE doesn't identify the image and link (beyond the higher list item), I have tried:
css=rbl:contains('option')
and
xpath=//span[url()='option/index?lfeCyc=Active']
Suggestions of what I should be using to identify the Target would be appreciated.
Edit:
I have added the javascript that triggers the link to be created.. So my Selenium IDE table source is below..
<tr>
<td>selectWindow</td>
<td>null</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>link=Publish</td>
<td></td>
</tr>
<tr>
<td>runScript</td>
<td>var path = $(this).attr('href'); if (e.which == 1 && !e.ctrlKey) {window.location = getCsBaseUrl() + "/" + path;} else {csNewWindow(path);</td>
<td></td>
</tr>
<tr>
<td>MouseOver</td>
<td>//div[contains(#class, 'rbl') and text()='Options']</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>//div[contains(#class, 'rbl') and text()='Options']</td>
<td></td>
</tr>
I guess perhaps my sequence or code is wrong, I have tried all possible combinations but no luck.
WebElement we = driver.findElement(By.cssSelector("div.rbl img"));
Then you could do
string attr = we.getAttribute("src");
Hope that helps
I have fudged a solution - but just using the open command for the links in question. It is not a standard mouseover, mousedown set of actions however it will do for now ;-)
ie command 'open' and Target:
/option/index