Unable to perform click action in selenium python

2019-01-25 14:01发布

问题:

I'm writing a test script using selenium in python. I have a web-page containing a tree-view object like this:

I want to traverse over the menu to go to the desired directory. Respective HTML code for plus/minus indications is this:

<a onclick="changeTree('tree', 'close.gif', 'open.gif');">
    <img id="someid" src="open.gif" />
</a>

The src attribute of the image can be either open.gif or close.gif.

I can detect weather there is a plus or minus by simply checking the src attribute of the img tag. I can also easily access to the parent tag, a, by using .find_element_by_xpath("..").

The problem is that I can't perform the click action not on the img nor the a tag.

I'v tried webdriver.Actions(driver).move_to_element(el).click().perform(); but it did not work.

I think I should mention that there is no problem in accessing the elements, since I can print all their attributes; I just can't perform actions on them. Any help?

EDIT 1:

Here's the js code for collapsing and expanding the tree:

function changeTree(tree, image1, image2) {
    if (!isTreeviewLocked(tree)) {
        var image = document.getElementById("treeViewImage" + tree);
        if (image.src.indexOf(image1)!=-1) {
            image.src = image2;
        } else {
            image.src = image1;
        }

        if (document.getElementById("treeView" + tree).innerHTML == "") {
            return true;
        } else {
            changeMenu("treeView" + tree);
            return false;
        }
    } else {
        return false;
    }
}

EDIT 2:

I googled for some hours and I found out that there is a problem about triggering the javascript events and the click action from web-driver. Additionally I have a span tag in my web-page that has an onclick event and I also have this problem on it.

回答1:

After some tries like .execute_script("changeTree();"), .submit(), etc, I have solved the issue by using the ActionChains class. Now, I can click in all elements that they have java-script events as onclick. The code that I have used is this:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get('someURL')
el = driver.find_element_by_id("someid")
webdriver.ActionChains(driver).move_to_element(el).click(el).perform()

I don't know if it occurred just to me or what, but I found out that I should find the element right before the key command; otherwise the script does not perform the action. I think it would be related to staling elements or something like that; anyway, thanks all for their attention.