简体   繁体   中英

Python Selenium: Click a href=“javascript:()”

I am using chromedriver and I have the following webpage source:

<form id="stepLinksForm" name="stepLinksForm" method="POST" target="mainFrame"> 

  <ul> 
      <li> <a href="javascript:submitLink('action_one.htm')">Action One</a> </li>
      <li> <a href="javascript:submitLink('action_two.htm')">Action Two</a> </li>
      <li> <a href="javascript:submitLink('action_three.htm')">Action Three</a> </li>
  </ul>   

</form>

After clicking anyone of the href, the browser goes to a new page but the url stays the same. What I want to achieve is clicking the first href, ie <li> <a href="javascript:submitLink('action_one.htm')">Action One</a> </li>

I have tried find_element_by_xpath, link_text and some other methods suggested on the Internet but none of them works. I really appreciate if someone could help.

To click on the first href with text as Action One you can use either of the following options ( Python Language Binding Art ) :

  • linkText :

     driver.find_element_by_link_text("Action One").click() 
  • cssSelector :

     driver.find_element_by_css_selector("a[href*='action_one.htm']").click() 
  • xpath :

     driver.find_element_by_xpath("//a[contains(@href,'action_one.htm') and contains(.,'Action One')]").click() 

Update

As you are unable to locate the element through LINK_TEXT , CSS , XPATH and even after time.sleep() it is pretty much confirmed that the element is within an frame which is denoted by the <frame> tag.

Now as you are able to see them by "Inspect" , locate the element within the HTML DOM and traverse up the HTML . At some point you will find a <frame> tag. Grab the attributes of the <frame> tag and switch to the intended frame first and then try to use the Locator Strategies provided in my answer. Here you can find a detailed discussion on How can I select a html element no matter what frame it is in in selenium?

Instead of click you can call the javascript code directly:

browser.execute_script("submitLink('action_one.htm')")

which equivalent to javascript:submitLink('action_one.htm')

Or you can find the a by its text:

browser.find_elements_by_xpath("//a[contains(text(), 'Action One')]")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM