首页 > 解决方案 > 如何通过 Selenium 找到元素

问题描述

我将 Selenium 与 PHP WebDriver 一起使用。我正在尝试单击导航栏中的链接,该链接显示在 HTML 中,如下所示:

<li class=""><a href="javascript:;" showpage="cards"><i class="zzdi zzdi-closed-caption zzdi-hx-fw"></i> User Cards</a></li>

我正在尝试选择元素然后单击它。但是,当我尝试按如下方式使用 xpath 时:

//a[@showpage="cards"]

或者

//*[@showpage="cards"]

我收到以下错误:

没有这样的元素:无法找到元素:{"method":"xpath","selector":"/*[@showpage="cards"]"}(会话信息:chrome=70.0.3538.110)(驱动程序信息:chromedriver =2.43.600233 (523efee95e3d68b8719b3a1c83051aa63aa6b10d),platform=Linux 4.15.0-43-generic x86_64) (警告:服务器未提供任何堆栈跟踪信息)命令持续时间或超时:24 毫秒有关此错误的文档,请访问: http: //seleniumhq.org/exceptions/no_such_element.html构建信息:版本:'3.4.0',修订:'未知',时间:'未知'系统信息:主机:'ubuntu',ip:'127.0.1.1',os.name:'Linux',os.arch : 'amd64', os.version: '4.15.0-43-generic', java.version: '1.8.0_191' 驱动信息: org.openqa.selenium.chrome.ChromeDriver Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false ,平台=LINUX,acceptSslCerts=false,goog:chromeOptions={debuggerAddress=localhost:43431},acceptInsecureCerts=false,webStorageEnabled=true,browserName=chrome,takeScreenshot=true,javascriptEnabled=true,setWindowRect=true,unexpectedAlertBehaviour=,applicationCacheEnabled=假,可旋转=假,networkConnectionEnabled=假,铬= {chromedriverVersion = 2.43.600233(523efee95e3d68b8719b3a1c83051aa63aa6b10d),userDataDir=/tmp/.org.chromium.Chromium.Teyqo7},takeHeapSnapshot=true,pageLoadStrategy=normal,databaseEnabled=false,handlesAlerts=true,version=70.0.3538.110,browserConnectionEnabled=false,nativeEvents=true,locationContextEnabled=true,cssSelectorsEnabled =true}] 会话 ID:367080a50b61c75a8c16a17b954a5972 *** 元素信息:{Using=xpath, value=/*[@showpage="cards"]}

任何有关如何使用 xpath 或如何使用任何其他使我能够单击链接的选择方法的帮助将不胜感激。

标签: phpseleniumxpathcss-selectorswebdriverwait

解决方案


您可能需要等待元素能够单击它:

$driver->wait()->until(
  WebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath('//a[@showpage="cards"]')))->click();

推荐阅读