How to access link InnerHTML using Selenium? - visual-studio-2010

I am trying to click on this link using selenium IWebDriver commands. I do not have access to the commands that I did when I was trying to use the browser control.
<a href="#" onclick="recentlyVisitedSelect('pages/VIEW/UTMEntry.aspx?USParams=PK=ESS!MenuID=2147!PageRerId=2147!ParentRerId=72','72','2147','2147', false, false, 'Time Clock Entry', true)" title="Time Clock Entry">
Time Clock Entry</a>
The way I gained access to this link in the browser control was...
HtmlElement link = (from HtmlElement elem in webBrowser1.Document.GetElementsByTagName("a")
where elem.InnerHtml == "Time Clock Entry"
select elem).ElementAt(0);
link.InvokeMember("Click");
The most recent failed attempt I have made using selenium is...
string elemHTML = browser.FindElement(By.LinkText("Time Clock Entry")).GetAttribute("innerHTML");
And...
IWebElement TCE = browser.FindElement(By.Id("Time Clock Entry"));
TCE.Click();
It would be simple I think, if I could figure out a way to access the InnerHTML.
Thank you for any assistance.

I would just select by css selector using the title and tag.
By.cssSelector("a[title='Time Clock Entry']");

Related

How do I let Selenium driver click on link which is dynamically created through JavaScript

I am trying to automate actions and unable to select an element due to its dynamic nature.
I am running Selenium web driver on ruby and am trying to select value that is not present in page source.
<a class="linkOtherBrowser" onclick="addChangeStatusField('InitialSelectionPage');submitFormByAction('ChangeStep');return false;" href="#"><div class="processBarElement noSelected">
<div class="whiteBeforeProcessBarTitles"></div>Initial Selection</div>
<div class="endOfElementOfProcessBar"></div></a>
I am trying to select value "Initial Selection" from above.
Could anyone pls help out?
Thanks,
Abhishek
As the HTML is generated by Javascript, You need to inspect the DOM instead of viewsource and write the element locator code accordingly.
Note: In IE, Firefox or Chrome you can press F12 key to see the developer tools and use the inspect element option to check the DOM.
Whatever element is generated dynamically is added in your DOM. WebDriver has capability of clicking on elements are the visible on UI and hence if the generated element is visible to regular user's you can click on the element easily.
To do so, you need to identify the best selector for that newly generated click, could be xpath or css. Once you identify the selector you can consider clicking clicking using following code
WebElement element = driver.findElement(By.xpath("//a[#title='NAME_TITLE']"));
element.click();
OR
WebElement element = driver.findElement(By.css("a[title='NAME_TITLE']"));
element.click();
There are more options within your By.class on picking the element in best way

Closing a popup box in Google Translate

I am new to NUNIT and am stumped on how to close a dialog box.
The site I am experimenting with is Google Translate. Part of the code "clicks" on the "Send Feedback Link".
Below is the function I am using:
public void CloseModalWindow(string className)
{
WebController wPage = new WebController(driver);
wPage.waitUntilExistsByXPath(className);
wPage.waitUntilVisibleByXPath(className);
IWebElement clickButtonXPATH = driver.FindElement(By.XPath(className));
clickButtonXPATH.Click();
}
The basic logic is that I am trying to simulate is to click the "X" on the upper right hand side of the Google Feedback popup that appears.
Please note that:
The web driver is FireFox.
I am sending the XPath value (derived from Google Translate directly using FireBug) /html/body/div[3]/div/span[2].
I've also tried using the CSSSelector method instead of XPATH, sending the value span[class='modal-dialog-title'] into the function.
Nunit will in complete without any errors, but the popup does not close as I am anticipating.
Thank you in advance for your input and insight.
From your XPath I see that the "X" is not a natively clickable element - like <a> or <button> are. I experienced that calling Click() on such elements does not what one expects. Instead you could try using the action builder functionality which will simulate a general mouse or keyboard input. Replace
clickButtonXPATH.Click();
with
new Actions(driver).Click(clickButtonXPATH).Build().Perform();

Selenium webdriver can't find button

EDIT:
I have cleaned this up a bit.
I have a button that looks like this:
<input id="applyRuleButton" class="Button" name="filtersContainer:applyRuleButton"
value="Apply" onclick="wicketShow('applyRuleButton--ajax-indicator');var
wcall=wicketSubmitFormById('id256', '?wicket:interface=:23:form:filtersContainer:applyRuleButton:
:IActivePageBehaviorListener:0:&wicket:ignoreIfNotActive=true',
'filtersContainer:applyRuleButton' ,function() { ;wicketHide('applyRuleButton--
ajax-indicator');}.bind(this),function() { ;wicketHide('applyRuleButton--
ajax-indicator');}.bind(this), function() {return
Wicket.$$(this)&&Wicket.$$('id256')}.bind(this));;; return false;" type="submit">
Firebug:
<input id="applyRuleButton" class="Button" type="submit"
onclick="wicketShow('applyRuleButton--ajax-indicator');var
wcall=wicketSubmitFormById('id2ee',
'?wicket:interface=:29:form:filtersContainer:applyRuleButton::IActivePageBehaviorListener:0
:&wicket:ignoreIfNotActive=true', 'filtersContainer:applyRuleButton' ,function() {
;wicketHide('applyRuleButton--ajax-indicator');}.bind(this),function() {
;wicketHide('applyRuleButton--ajax-indicator');}.bind(this), function() {return
Wicket.$$(this)&&Wicket.$$('id2ee')}.bind(this));;; return false;" value="Apply"
name="filtersContainer:applyRuleButton">
I'm trying to click it and have tried pretty much everything for 2 days, webdriver does not find the element, IDE does find it:
//This was my first approach, it should work.
It works in IDE, but not Webdriver:
driver.findElement(By.id("applyRuleButton")).click();
//then perhaps this should do the trick, hint: It doesn't:
WebElement element3 = driver.findElement(By.id("applyRuleButton"));
JavascriptExecutor executor3 = (JavascriptExecutor)driver;
executor3.executeScript("arguments[0].click();", element3);
Ok, Id not working, I get it.
Then this should work at least:
driver.findElement(By.xpath("//table/tbody/tr/td/div/div/table/tbody/tr[6]/td/input[#id='applyRuleButton']")).click();
It feels like I am missing something obvious here, some help please?
Additional information:
I have added a 5 second wait, the page is completely loaded.
This button is located in a table:
The Xpath is
/html/body/div[4]/div[2]/form/div[3]/div/div/table/tbody/tr/td/div/div/table/tbody/tr[6]/td/input
Webdriver error, no matter what I throw at it, is: Unable to locate element
I have used both 'click' and 'submit', still no success.
I think in this case there are two possibilities :
Either there is another element having same id/xpath.
OR Element present in another iframe.
Is the button visible. Selenium click (latest firefox 26 and latest webdriver 2.39.0) does not sometimes implicitly scroll; Or it may not scroll it fully. So scroll it into view - Scroll Element into View with Selenium and then it should work.
Note Selenium Best Practise try to use By.Id,By.CSSSelector and if nothing gets use By.Xpath in the order of priority. ( Use the FireFinder, FireBug plugin to test XPath or CSS)
This might be a synchronization issue. Such issues can be solved using smart waits.
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists((By.Id("applyRuleButton"))));
WebElement element3 = driver.findElement(By.id("applyRuleButton"));
And that should work perfectly fine.
There is absolutely nothing wrong with your selector. I just don't think you're invoking the click correctly.
Try:
driver.findElement(By.id("applyRuleButton")).click();
If this doesn't work, then you might have to invoke a WebDriverWait since you have this question marked as [ajax]
Could you post the entire html?
As a simple experiment, I took the html snippet that you posted and wrote a short python script that invokes selenium:
from selenium import webdriver
br = webdriver.Firefox()
br.get("put your path to snippet here")
button = br.find_element_by_id("applyRuleButton")
print button.get_attribute("name")
button.click()
br.close()
I can find the button and extract the attribute "name" which prints "filtersContainer:applyRuleButton". This is admittedly a very limited experiment, but it suggests that the issue is related to not being where you think you are on the page.
Try this:
driver.findElement(By.Name("filtersContainer:applyRuleButton"));
If this doesn't help, check whether this button is located in any other frame. If so, you may have to find and move your focus to that frame and then locate this button.
First try to identify the button by writting correct xpath using firebug, if you are able to identify button by that xpath then use that xpath while writing your script.
driver.findElement(By.xpath("//input[# type='submit' and # id='applyRuleButton'")).click();
This is ajax application use proper explicit/ webdriver wait till the button gets downloaded
I see that this thread is old, but I was looking at it today (Sept/2021) as I was having the same problem: I could see the name / id/ type of the button, but it would never be found.
I discovered that when I had clicked in a prior link, it opened a new tab in my browser, but Selenium did not change the focus to the new tab, so it couldn't find the ID of the button I was looking for.
I solved it with :
driver.find_element_by_id("export").click() #driver
time.sleep(2)
driver.switch_to.window(driver.window_handles[1]) # Change focus to the new tab
driver.find_element_by_id("0001btn").click() #click
driver.close() #close new tab
switching to a specific frame helped me to resolve the same issue. (python + selenium)
I installed the Selenium Recorder extension on chrome and recorded my steps, and found out that the recorder had a step to select a frame = 0, so adding
self.home_page.driver.switch_to.frame(0)
self.home_page.click_on_element_by_id("clickSubmit")
solved the problem.

How to handle google search ajax data using selenium

How to handle google search ajax data using selenium (Type some string in google search, do not press enter key and check matching string data in search text box) ? How to get this data using selenium RC/Webdriver ?
If you know that the action of some event (e.g. sendKeys, onClick, whatever) is going to trigger some event - like an Ajax request - you should be using waitFor until your condition is met (see the Advanced Usage guide).
To avoid supplying a brittle timeout threshold on your test, you may want to call this in a Poll implementation, say once every 500ms 10 times for example, and then pass/fail accordingly
FitLibraryWeb has some nice, clean abstractions for this, but you'd need to use Fitnesse of course
Thank u friends .. I am able to run a google search from selenium example code using firefox driver : http://seleniumhq.org/docs/03_webdriver.html#introducing-the-selenium-webdriver-api-by-example
Now i am trying to click on 'Change Location' available in left side pane after getting the search result but no luck. Code sample :
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!");
element.submit();
WebElement expandLocation = driver.findElement(By.id("expand_location_link"));
expandLocation.click();
Debug info:
In view source i am not able to see the element expand_location_link but is visible in element inspect section of firefox/chrome or after saving the page from browser to local system.

How can I automate a google link on the page I am working on using watir-webdriver?

Page link I am working on is http://www.whatcar.com/car-news/subaru-xv-review/260397
I am trying to automate 'clicking the google link' but am having no luck and keep receiving an error.
Link HTML:
<a tabindex="0" role="button" title="" class="s5 JF Uu" id="button" href="javascript:void(0);" aria-pressed="false" aria-label="Click here to publicly +1 this."></a>
My code:
#browser.link(:class, "s5 JF Uu").click
Error message:
unable to locate element, using {:class=>"s5 JF Uu", :tag_name=>"a"} (Watir::Exception::UnknownObjectException)
./step_definitions/11.rb:12:in `/^On the page I click 'Twitter' , Facebook and Google button$/'
11.feature:8:in `When On the page I click 'Twitter' , Facebook and Google+ button'
The link is inside a frame. To make it even more fun, frame id is different every time the page is refreshed.
browser.frames.collect {|frame| frame.id}
=> ["I1_1323429988509", "f3593c4f374d896", "f4a5e09c20624c", "stSegmentFrame", "stLframe"]
browser.refresh
=> []
browser.frames.collect {|frame| frame.id}
=> ["I1_1323430025052", "fccfdf9410ef34", "f11036dad706668", "stSegmentFrame", "stLframe"]
I1_1323429988509 and I1_1323430025052 is the frame. Since I1_ part is always the same, and no other frame has that, you can access the frame like this:
browser.frame(:id => /I1_/)
Since there is only one link inside the frame:
browser.frame(:id => /I1_/).as.size
=> 1
You can click the link like this:
browser.frame(:id => /I1_/).a.click
Or if you prefer to be more explicit
browser.frame(:id => /I1_/).a(:id => "button").click
That will open a new browser window, and a new challenge is here! :)
The technical answer:
The class of the button on the page that you linked is different for me than the class that you list. It looks like it behaves differently based on the cookies on your local machine (which would be absent during a Watir-driven Firefox or IE session).
You would need to find a different element that is not dynamic to hook into.
The ethical answer:
It is questionable that you are attempting to automate the promotion of online articles through social media. Watir/Watir-Webdriver is not a spam bot, and the services you are using specifically prohibit the use of automation/bots.
That 'button' link is inside an iframe. Read on the watir Wiki how to deal with stuff in frames. If that's not enough to get it working please edit the answer with revised code and error etc and we can work it forward from that point.

Resources