简体   繁体   中英

clicking on a link with the same href value using selenium python

I have a html code that has two links but both the links have the same href value, but the onclick and the text are different. I wasn't sure as to how to access the second link. I tried using driver.find_element_by_link_text('text'), but I get a no such element found error.

<div id="member">
    <"a href="#" onclick="add_member("abc"); return false;">run abc<"/a> 
    <br>
    <"a href="#" onclick="add_member("def"); return false;">run def<"/a>
</div>

There are multiple options to get the desired link.

One option would be to get use find_element_by_xpath() and check onclick attribute value:

link = driver.find_element_by_xpath('//div[@id="member"]/a[contains(@onclick, "add_member(\"def\")")]')
link.click()

Another one would be to simply find both links and get the desired one by index:

div = driver.find_element_by_id('member')
links = div.find_elements_by_tag_name('a')
links[1].click()

Which option to choose depends on the whole HTML content. Hope at least one of two suggested solutions solves the issue.

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