python - 如何使用 Python 在 Selenium 中为给定的 HTML 构建 xpath

标签 python selenium selenium-webdriver xpath webdriver

我正在使用 Selenium 和 python 在 telegram web 上执行操作,我获取网页,选择正确的组,但是当我尝试输入时,我必须单击“确定”或“取消”,我想单击好的,但我不知道正确的方法!

情况是:

<button class="btn btn-md btn-md-primary" 
ng-switch="type" ng-click="$close(data)" 
ng-class="{'btn-md-danger': type == 'RESET_ACCOUNT' || type == 'HISTORY_LEAVE_AND_FLUSH' 
|| type == 'HISTORY_FLUSH_AND_DELETE' || type == 'HISTORY_FLUSH'}" my-focused="">
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!----><span ng-switch-default="" my-i18n="modal_ok" class="" style="">OK</span><!---->
</button>

xpath 是://*[@id="ng-app"]/body/div[6]/div[2]/div/div/div[2]/button[2]/span

我尝试了很多不同的配置,从最简单的 browser.find_element_by_tag_name('//span[text()="OK"]').click 开始一些奇怪的事情browser.find_element_by_xpath('//div[6]/div[2]/div/div/div[2]/button[2][contains(@span, "ng-switch-default")]').click但我不知道如何单击 <span> 中的“确定”标签

最佳答案

根据您共享的 HTML,单击文本为 OK 的元素,因为它是 Angular元素,您必须诱导 WebDriverWait 才能使 元素可点击,如下所示:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC    
# other lines of code
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-md btn-md-primary' and @ng-switch='type']//span[contains(.,'OK')]"))).click()

关于python - 如何使用 Python 在 Selenium 中为给定的 HTML 构建 xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50737246/

相关文章:

python - 如何在 Debian Linux 上为 python 2.5 安装 SSL?

python - 这个 Bokeh 列数据源是如何工作的?

java - Selenium 2 和 OperaDriver : java.net.BindException

python - 是否有库函数可以检查 MAC 地址是否是多播的?

Python:Pandas 系列 - 以秒为单位的连续日期时间行之间的差异

Java/ Selenium : Simple program to open Edge fails (dependency issue?)

java - 为什么不弹出警报?

java - Selenium IE 驱动程序找不到新打开的窗口

java - 使用java同时建立多个数据库连接和查询时是否应该使用同步?

java - 在文本字段中输入明天的日期