shong555
shong555

Reputation: 49

Select Link in Table Rows using Selenium for Python

I am looking to click a link using Selenium in Python. The link is contained within a table that has a dynamic number of rows, and I want to select the link for "Job Created" based on the most recent date. The tricky part is that the link is not the date itself, but a separate column on the row.

Table format is as below:

enter image description here

A possible solution I could do is to do a: button = find_elements_by_link_text("Job Created"), then specify button[0].click() , but I would prefer if there would be a way to select the Job Status link based on the creation time.

Sample code for table:

                <tr>
                <!--td>1</td>
                <td></td-->
                <td>2018/12/1 16:12:33 UTC</td>
                <td><a target="_blank" href="/sample/sample">Job Created</a></td>

Thanks!

Upvotes: 0

Views: 2221

Answers (1)

QHarr
QHarr

Reputation: 84465

In the absence of more HTML and/or the URL I hope the following is helpful from a possible logic point of view. I selected a website with a table that has a price column (This is a substitute for datetime) and a column with text to match on. Hopefully my attempt won't be judged too harshly.

I outline the steps that I think are similar to your problem i.e.

  1. Use xpath to select two lists where one list is a tag elements matched by text and the other is the preceding::td[1] . In your example I think possible xpaths are:

//a[text()="Job Created"]/preceding::td 
//a[text()="Job Created"]
  1. You take the text from the first list and treat as required. You would need a function to format your datetimes ready for sorting. The second list is kept as elements so can later be clicked on. This assumes that your datetimes can be treated and sorted in an acceptable fashion.

  2. Combine these in a single list of tuples and then sort on the first in each tuple

So, an outline with my admittedly not perfect case study:

from selenium import webdriver
from operator import itemgetter

url ="https://www.wiseowl.co.uk/dax/london/"
driver = webdriver.Chrome()
driver.get(url)

#used title myDates although in my example I am using prices
myDates =[int(element.text.strip('£')) for element in driver.find_elements_by_xpath("//a[text() = 'Book places']/preceding::td[1]")]
myData = [element for element in driver.find_elements_by_xpath("//a[text() = 'Book places']")] #links in adjacent column

combined = list(zip(myDates,myData))
combined = sorted(combined,key=itemgetter(0), reverse=True) #sort list on first 'column'
combined[0][1].click()  #click first in descending list

#other code
# driver.quit()

Upvotes: 1

Related Questions