如何使用Selenium(Python)单击表内的按钮

时间:2018-08-01 16:05:37

标签: python selenium

<table _ngcontent-c19="" class="table">
  <tbody _ngcontent-c19="">
    <tr _ngcontent-c19=""><!---->
      <td _ngcontent-c19="" class="ng-star-inserted">
        <div _ngcontent-c19="" class="span3" style="height: auto;">
          <div _ngcontent-c19="" class="text-center" style="visibility: visible;">
            <button _ngcontent-c19="" class="b1" type="submit">Click This</button>
          </div><!---->
        </div>
      </td>
    </tr>
  </tbody>
</table>

我正在尝试使用SELENIUM单击表内的按钮。

我编写的代码是

driver.find_element_by_xpath("//*[contains(getText(),'Click This')]").click()

driver.find_element_by_class_name('b1').click()

它们都抛出“未找到元素异常”

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此 xpath

wait = WebDriverWait(driver,30)
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'Click This') and @class='b1']"))).click()

请注意,您必须导入:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC 

答案 1 :(得分:0)

因为您的代码运行速度比浏览器快,所以您需要告诉他等到元素可见并且可点击为止。

button = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, "//button[text()='Click This']"))
button.click()