How to select the element in HTML tags based on its text in Behat? - behat

I'm running the following Behat scenario:
Then I should see "Testing body" in the "strong" element
for the following HTML snippet:
<strong>Testing body</strong>
However I am getting an error:
The text "Testing body" was not found in the text of the element matching css "strong"
What is the best way to check if element contains below tags?
<em>Testing body</em>
<ol><li>Testing body</li>
</ol>
<ul><li>Testing body​​​​​​​</li>
</ul>
I am trying to use wysiwyg.feature with syntax:
Then I should see "Testing body" in the "<Element>" element with the "<Property>" CSS property set to "<Value>" in the "Pearson Content" region

Make sure the selector used is unique.
Depending on the method used you might need id|name|label|value or css selector.
I your case the selector used is too general, you need to narrow the section by adding an extra element in front of this to tell him to search in a smaller section.
For example: #myid strong -> will search strong in the element that has the id myid
Same thing for the other elements, you could have ol>li or ul>li, but if more elements are found you will need to add an extra selector in front to narrow the section.
Always check the CSS manually in the browser and make sure is unique or the element that you need is found first.
If you want to check for an element that contains some text, you could use XPath like this:
//strong[contains(text(), 'Testing body')]
You can also use a css if you can identify this section as I said above, but I need more from the html, a large section in order to get a better selector.

The following method may help:
/**
* #Given I should see :text in the :tag element
*/
public function iShouldSeeInTheElement($text, $tag) {
$this->verifyElementByXpath("//${tag}[contains(text(), '${text}')]");
}
Instead of contains, you can also use starts-with and other.
Note: I haven't tested it, so please suggest improvements if you do.

Related

Problems extracting elements by class names with Selenium

From this page: https://www.realestate.com.kh/buy/, which looks like this in the inspector:
I'm trying to extract all elements of class css-1uuzwjq eq4or9x0 into a list in order to click on the elements and further explore.
I have this code, in which I try to get the elements by their Xpath:
ads = browser.find_elements_by_class_name('css-1uuzwjq eq4or9x0')
for ad in ads:
ad.click()
However, the list always ends up empty. What am I doing wrong?
class attribute holds multiple classes , each class is separated by space. In your case, 'css-1uuzwjq eq4or9x0' are two classes not one
you can find it as :#
xpath
in xpath it validates the class attribute value is exactly the same
//*[#class="css-1uuzwjq eq4or9x0"]
CSS
in css it checks for element that contains both the mentioned class, each class should be mentionedwith a dot
.css-1uuzwjq.eq4or9x0
if you want exact match , use the below locator as it checks the class attribute value to be exact
[class="css-1uuzwjq eq4or9x0"]
using class locator
browser.find_elements_by_class_name('css-1uuzwjq.eq4or9x0')
calss locator uses css locator under the hood , so when you pass a class name, it just adds 'dot' in front of it . so to make it a valid locator pass all classes by replacing space with dot
//div[#class='list']/div[./header[contains(#class,'featured')]]
I would use this xpath to obtain all the divs needed to search.
use /div/header/a if you want the a tag to click.
So it would be
driver.get('https://www.realestate.com.kh/buy/')
hrefs=[x.get_attribute('href') for x in driver.find_elements(By.XPATH,"//div[#class='list']/div/header/a")]
print(hrefs)
for href in hrefs:
driver.get(href)
Would retrieve all the hrefs to loop and will prevent using driver.back() and all the stale elements you will get.
I would not recommend getting by class name because they seem dynamic also those are multiple class names which are grabbed by a css selector.
css-1uuzwjq eq4or9x0 -> .css-1uuzwjq.eq4or9x0

How to locate random id generated by a modal?

I was testing my website using RF. The problem is, every time the modal is opened, a different id(locator) will be set on the textbox that I want to input my text. How do you get value of this locator?
I was supposed to try Get Element Attribute but then it cannot support my problem since it still requires a specific locator.
In ROBOT Framework (RF), the locator can be accessed by several ways. Please refer and read this link: http://robotframework.org/Selenium2Library/Selenium2Library.html
The most common way to access the locator is by id such as :
Input Text id:username # Element with id 'username'.
Input Text id:password # Element with id 'password'. you can also use 'Input Password' keyword.
However, if the 'id' element is so dynamic which it keep changing, then the best alternative is to use either ABSOLUTE XPATH expression or CSS selectors. Install the XPATH add-on in your web browser. For firefox, just install ChroPath.
Then, get the ABSOLUTE Xpath element of that username & password text box. Let's assume we know the absolute xpath expression already, so in ROBOT, you can write like below.
${login_absolute_xpath}= Set Variable xpath=/html[1]//div[7]/form[1]/div[1]/input[1]
${password_absolute_xpath}= Set Variable xpath=/html[1]//div[7]/form[1]/div[2]/input[1]
Wait Until Page Contains Element xpath=${login_absolute_xpath}
Input Text xpath=${login_absolute_xpath}
Input Text xpath=${password_absolute_xpath}
...
This should works. Please let me know if this helps.

Capybara: Find element by attribute containing something NOT

I am having the following issue in my Capybara environment:
I need to search for an element. This element contains an attribute, which is unique. The attribute is changed asynchronously.
I need the content of this attribute, but when I just search for the attribute I am getting a nil.
I could wait until the attribute has the property, but since this is Capybaras job, I thought there might be a possible selector, which can search for something like:
find('button[uniqueattribute] != nil')
Any ideas how to do this?
Thanks already!
If the attribute is being added to the button element (didn't have the attribute originally) then you can just do
find('button[attribute_name]')
which will wait (up to Capybara.max_default_wait_time seconds for a button element with that attribute to be on the page - https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors. To wait and then get the contents/value of that attribute you could do
find('button[attribute_name]')['attribute_name']
If you just want to wait until the attribute is either not there or not blank then you can do
find('button:not([attribute_name=""])')
If you need to ensure the attribute is there, but isn't blank it would be
find('button[attribute_name]:not([attribute_name=""])')
I found a possible solution:
You can check the length of an element by Xpath (which is awesome) with string-length.
So in my case the solution was:
find(:xpath, ".//button[#unique_attribute_name[string-length() != 0]]")
Now Capybara waits until the attribute has a value. If there are more pretty solutions, just tell me.

Concise Xpath to simulate finding an element regardless of page structure? (selenium)

If you're visually looking at a webpage and there is something clickable and unique on the page, you'll just click it. Without thinking about the page structure.
I'm interested to see what the most concise xpath is that could be constructed to simulate this in a versatile manner.
For example, target the "I'm feeling Lucky" button on the Google homepage:
//*[contains(#*, 'Lucky')]
The above works. But would fail in the element contained Lucky as inner text, or if the wrong case was specified. As such, our xpath needs to cater for any sensitivity and also look for the given string matching inner-text as well.
How could the above xpath be expressed in the most concise yet encompassing structure?
There is nothing thats very generic and executing such xpaths could be costly also at times.
"//*[contains(#*, 'Lucky')] | //*[contains(text(), 'Lucky')]"
Above is one xpath you can combine to get some results. You start specifying which nodes you don't to examine or ones which you want to examine
"//*[contains(#*, 'Lucky')] | //*[contains(text(), 'Lucky')][not(self::script|self::td)]"
And you can keep improving it
It's not possible to create a versatile XPath to accurately/reliability locate an element by text.
Why?
Because the text evaluated by an XPath is not necessary rendered in the page.
Because there's a hight chance to end-up with multiple matches since each ancestor also contains the expected text.
But mainly because there's too many rules/specific cases to consider.
But if I had to create one, then I'd start with this one:
"(html/body//*[not(self::script or self::style)][contains(concat(#value, normalize-space()), 'MyText')])[last()]"
Get all the descendants of the <body>
html/body//*
except <script> and <style>
[not(self::script or self::style)]
where the value attribute or normalize html contains 'MyText'
[contains(concat(#value, normalize-space()), 'MyText')]
then returns the last and deepest match
[last()]

not able to find element using id in findelement in selenium

I am not able to find the element using "id" in selenium as the id is randomly changing in every session of execution so the same id i am not getting in next execution.
As there is no other unique property is there to identify the element.
code sample
You didn't specify a language so I'm going to give you Java. You can do this by using the CSS class or probably a better choice (because of likely uniqueness) is data-lynx-name.
By CSS class
driver.findElement(By.cssSelector("div.http-lynx-json-org-text-input"));
By attribute
driver.findElement(By.cssSelector("div[data-lynx-name='username']"));
You really should read the question that I duped this one to:
Find element by attribute
Also read more about CSS selectors,
http://www.w3.org/TR/selectors/#selectors
You can use XPath.
String xpath = //div[#data-lynx-name='usernameLabel'][text='User ID']/following-sibling::div[1]
The above XPath will will find the div tag containing text 'User ID' and finds the next div which is is the required textbox.
It seems that you can even use the attribute 'data-lynx-name' attribute of the textbox div tag directly.
String xpath = //div[#data-lynx-name='username']
Selenium
driver.findElement(By.xpath(xpath));