1

I'm trying to select dynamic links in a JavaScript table using Selenium. Here is sample HTML code for one of the links I'm trying to click:

<a href="#" onclick="javascript: runCategoryReport(0,&quot;objectName=enrollee&amp;titleMessageKey=3-3-2&amp;time=month&amp;systemTypeMetaId=6&amp;categoryName=Attendee&quot;);">1925</a>

I've tried the following lines of code separately to click this specific link:

Option 1

driver.find_element_by_xpath("//a/*[contains(text(), '3-3-2')]").click()

Option 2

driver.find_element_by_xpath("//a[contains(@onclick, '3-3-2')]").click()

Both lines of code result in errors:

NoSuchElementException: Message: no such element: Unable to locate element {"method":"xpath","selector":"//a/*[contains(text(), '3-3-2')]"} (Session info: chrome=90.0.4430.212)

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[contains(@onclick, '3-3-2')]"}
  (Session info: chrome=90.0.4430.212)

I'd appreciate any kind of feedback on this issue.

MendelG
  • 14,885
  • 4
  • 25
  • 52
Russell C
  • 11
  • 2

2 Answers2

0

Try using a an attribute CSS selector: a[onclick*='3-3-2'], which will find an a tag who has an attribute onclick that contains '3-3-2'.

driver.find_element_by_css_selector("a[onclick*='3-3-2']").click()
MendelG
  • 14,885
  • 4
  • 25
  • 52
  • Thank you for the recommendation! I tried it out and unfortunately received an error similar to what I mentioned above: NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"a[onclick*='3-3-2']"} (Session info: chrome=90.0.4430.212) – Russell C May 24 '21 at 13:26
  • @RussellC Try waiting for the element to appear. See [this](https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable) post. – MendelG May 24 '21 at 22:16
0

I was able to solve my issue. I added the switch_to.frame code and replaced the find_element_by_xpath path with the link's full xpath.

Here is the final code for anyone to reference:

driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))

driver.find_element_by_xpath("/html/body/div/table/tbody/tr/td/form[1]/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[4]/td[2]/div/font/a").click()
buddemat
  • 4,552
  • 14
  • 29
  • 49
Russell C
  • 11
  • 2