首页 > 解决方案 > 单击我在 python 中用 selenium 找不到的按钮

问题描述

我有这个 html 元素:

<button class="expedition_button awesome-button " onclick="attack(null, '6', 2, 0, '')"><div></div><div></div></button>

并且由于某种原因我的代码无法单击它...只是给了我一个关于未按类查找元素的错误...

有没有办法发送按钮的功能“onclick”按钮持有的信息?即向该按钮的功能发送信息-“attack(null, '6', 2, 0, '')”

或使用此信息查找按钮

试过 xpath 但我似乎找不到它.. 只是给了我这个:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div[2]/div/div[3]/div/div[2]/div[2]/div[2]/div[2]/div[2]/button

当我检查 xpath 时,我看到每次打开页面时它都会发生变化..

第一的 第二 第三

标签: pythonseleniumselenium-webdriver

解决方案


好的,所以我尽可能地把它放在一起,因为我没有用 Python 编码,所以我的语法在某些地方可能不正确,但我试着做对了,在任何一种情况下,逻辑都在那里并且注释应该解释我在做什么:

首先让我们获取容器 div:

//Get the container which holds the 4 divs and their buttons
containerDiv = browser.find_element_by_id('expedition_list')

//Get the divs which contain the buttons
containerDivs = containerDiv.find_elements_by_class_name('expedition_box')

//Iterate the containers
for val in containerDivs:
    //Get the div elements of the container
    childDivs = val.find_elements_by_tag_name('div')
    //iterate these divs, looking for the one which contains a button
    for val1 in childDivs
       buttonDiv = val1.find_elements_by_tag_name('button')
       //Check to see if we found a div with a button
       if len(buttonDiv) > 0
          for button in buttonDiv
          //If the button text is what we are looking for, click it
          if button.Text = 'whatever your button's text is'
             button.Click

推荐阅读