I'm trying to use Selenium with WebDriver and the Page Object Pattern to open links in a table. I do not have any control over the web page code.
Also please note, this is a simplified example however it does work and shows the issue.
Working Code: https://gist.github.com/charlesgreen/b80ed7e164b7199eaa44229e104f4428
The table has a column with 1 or 2 links in a single cell.
For cells with only 1 link, I am able to open the link by calling .link_element.click on the cell.
For cells with 2 links, this opens the first link in the cell but I am trying to open the second link (facts). Is there a way to click on only the Facts link in the cell (i.e. index or iteration)?
Note: The original website I am working with both links open however I am unable to reproduce the issue locally With this said, it is not my objective. I am trying to open the second link. This is reproducible in the code below along with the gist link above.
# products.rb
require 'selenium-webdriver'
require './product_page'
Selenium::WebDriver.logger.output = 'selenium.log'
Selenium::WebDriver::Chrome.driver_path = '/Applications/chromedriver'
browser = Selenium::WebDriver.for :chrome
# UPDATE File path
browser.get('file:///Users/name/products/index.html')
product_page = ProductPage.new(browser)
product_page.open_facts_link
# product_page.rb
require 'page-object'
class ProductPage
include PageObject
table(:products, id: 'products')
def open_facts_link
products_element[2][0].link_element.click
end
end
# index.html - validated with https://validator.nu/
<!DOCTYPE html>
<head>
<title>Link Page</title>
<script>
function OpenPhotos(val) {
var opened = window.open("");
opened.document.write("<html><head><title>Photos</title></head><body>Photos</body></html>");
}
function OpenFacts(val) {
var opened = window.open("");
opened.document.write("<html><head><title>Facts</title></head><body>Facts</body></html>");
}
</script>
</head>
<body>
<table id="products">
<tr>
<th>Links</th>
<th>Description</th>
</tr>
<tr>
<td>
<ul>
<li>
<a id="A_35" href="javascript:OpenFacts('35')" target="_blank">Facts</a>
</li>
</ul>
</td>
<td>Product 1</td>
</tr>
<tr>
<td>
<ul>
<li>
<a id="A_36" href="javascript:OpenPhotos('36')" target="_blank">Photos</a>
</li>
<li>
<a id="L_36" href="javascript:OpenFacts('36')" target="_blank">Facts</a>
</li>
</ul>
</td>
<td>Product 2</td>
</tr>
</table>
</body>
To click the different links in the same cell, you can pass a locator to link_element
to be more specific. In this case, you could use the href
attribute to differentiate the 2 links:
# Click Facts link
products_element[2][0].link_element(href: /OpenFacts/).click
# Click Photos link
products_element[2][0].link_element(href: /OpenPhotos/).click