MetroSynth
MetroSynth

Reputation: 43

Selenium/Python: JavaScript href refuses to execute

So, I am running Selenium on Python 3.5 attempting to click a button with a JavaScript function as its href. I have tried the solutions that helped others but my issue won’t budge.

Version Inventory:

The html of the button is below:

<tbody>
    <tr>
        <td>
            <a href='JavaScript:SWESubmitForm(document.SWEForm11_0,c_45,"s_11_1_0_0","")' tabindex="1700">Choose Account</a>
        </td>
    </tr>
    <tr>
        <td>View a different account</td>
    </tr>
</tbody>

Solutions I have tried all move to the correct element in the correct frame, and it appears as if the click is being performed without throwing any exceptions, but Selenium cannot get the script to run under any circumstance. This is baffling, as manually clicking the link in the open webdriver window operates flawlessly and loads the next page. I have JavaScript enabled through a webdriver.FirefoxProfile() object.

The below (albeit messy) xpath is the best way I have found to move to the correct element and this does find the correct element every single time, however it doesn't execute the script under any conditions.

choose_account = driver.find_element_by_xpath('//*[/html/body/table[3]/tbody/tr/td[3]/\
span[1]/form/table[2]/tbody/tr/td/table/tbody/tr/td/table[2]/tbody/tr[2]/td[2]/\
table/tbody/tr[1]/td/a]')

Method One [Failed]: Moving the mouse directly to the element and clicking. Method runs without throwing errors or exceptions. Page does not change. JS does not execute

action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(choose_account, 0, 0)
action.click()

Method Two [Failed with error]: Attempts running the script exactly as written in the href value of the element. Throws an exception:

driver.execute_script('SWESubmitForm(document.SWEForm11_0,c_45,"s_11_1_0_0","").click();')

The exception thrown:

ReferenceError: SWESubmitForm is not defined

Method Three[Failed]: Attempts using JavaScript executor on the element. Method runs without throwing errors or exceptions. Page does not change. JS does not execute

driver.execute_script("arguments[0].click();", choose_account)

Does anyone have any insight into what could be happening here? I'm really at a loss.

M

UPDATE: [RESOLVED] Thanks to Lauda for suggesting to use a simpler/cleaner style of locating the anchor tag using a unique snippet contained in its href and the find_element_by_xpath() method. The below code worked like a charm:

choose_account = driver.find_element_by_xpath("//a[contains(@href,'SWEForm11_0,c_45')]")
choose_account.click()

Upvotes: 4

Views: 2906

Answers (1)

lauda
lauda

Reputation: 4173

Try using a regular click with a better selector.

css: a[href*=SWESubmitForm]

xpath using partial href value: //a[contains(@href, 'SWESubmitForm')]

xpath using full href value: //a[@href='add_entire_href_value_here']

Upvotes: 2

Related Questions