【问题标题】:Selenium and Chrome, having trouble selecting elementSelenium 和 Chrome,在选择元素时遇到问题
【发布时间】:2017-11-01 15:15:23
【问题描述】:

我正在使用 Selenium 和 Chrome 编写脚本。我无法让 Selenium 选择并单击两个元素。这是我要选择的元素:

元素 1 的 HTML:

<td class="menuItem" id="tWlans" style=""><a href="frameWlan.html" 
id="cWlans" accesskey="W" onmouseover="highlight('Wlans')" 
onmouseout="removeHighlight('Wlans')" onclick="selectTab('Wlans')" 
onfocus="highlight('Wlans')" onblur="removeHighlight('Wlans')" 
target="mainFrame"><u>W</u>LANs</a></td>

元素 2 的 HTML:

<td class="listNoPad">  
<input type="TEXT" name="1.6.7.wlan_id" class="statictextboxlink" 
onclick="editThisWlan(this.value,this.name)" readonly="" size="7" value="7">
</td>

我尝试通过 id 和 XPath 选择元素,但都不起作用。

function siteNavigate() {
sleep(4500);
driver.findElement(By.xpath('//*[@id="cWlans"]')).click();  
//driver.findElement(By.id('cWlans')).click();
}

提前感谢您的任何帮助和建议。

编辑:

function helpAction(pageId, startpage) {
  var baseHref = window.location.href;
  var index = baseHref.indexOf("/screens");
  baseHref = baseHref.substring(0, index);

  var href = "/helpfiles/oweb/index.html";
  var editWindow = window.open(baseHref + href, "editWindow", "left=100 top=50 menubar=no,toolbar=yes,width=800,height=600,status=yes,resizable=yes");
  if (navigator.appName != "Netscape") {
    editWindow.location.href = baseHref + href;
    editWindow.location.reload(true);
  }
  editWindow.focus();
}

function feedbackAction() {
  var URL = 'http://www.cisco.com/go/wireless-feedback';
  var feedbackWindow = window.open(URL, "FeedbackWindow", "left=100 top=50 menubar=no,toolbar=no,scrollbars=yes,titlebar=yes,width=800,height=800,status=yes,resizable=yes");
  feedbackWindow.focus();
}

function selectTab(tabName) {
  // All this function does is update the value of the hidden field and call the updatePage() function
  // Obtain object reference to hidden field
  var fieldObj = document.getElementById("hSelectedTab");
  // Store the new tab selection in the hidden field
  fieldObj.value = tabName;
  updatePage();
}

function highlight(tabName) {
  //remove highlight for all the tabs
  removeHighlightAll();
  var highlightObj = document.getElementById("t" + tabName);
  // Only highlight if srcElement is a tab object.
  highlightObj.style.backgroundColor = "#25546B";
}

function removeHighlight(tabName) {
  var highlightObj = document.getElementById("t" + tabName);
  highlightObj.style.backgroundColor = "";
}

function removeHighlightAll() {
  document.getElementById("tMonitor").style.backgroundColor = "";
  document.getElementById("tWlans").style.backgroundColor = "";
  document.getElementById("tSwitch").style.backgroundColor = "";
  document.getElementById("tWireless").style.backgroundColor = "";
  document.getElementById("tSecurity").style.backgroundColor = "";
  document.getElementById("tManagement").style.backgroundColor = "";
  document.getElementById("tCommands").style.backgroundColor = "";
  document.getElementById("tHelp").style.backgroundColor = "";
  document.getElementById("tFeedback").style.backgroundColor = "";
}

function updatePage() {
  // Clear the current tab selection
  removeSelection();
  // Obtain object reference to hidden field
  var fieldObj = document.getElementById("hSelectedTab");
  // Retrieve the selected tab
  var selectedTab = fieldObj.value;
  // Highlight the selected tab
  cellObj = document.getElementById("t" + selectedTab);
  cellObj.className = "selected";
}

function removeSelection() {
  removeHighlightAll();
  // Brute force method to clear the tab selection
  document.getElementById("tMonitor").className = "menuItem";
  document.getElementById("tWlans").className = "menuItem";
  document.getElementById("tSwitch").className = "menuItem";
  document.getElementById("tWireless").className = "menuItem";
  document.getElementById("tSecurity").className = "menuItem";
  document.getElementById("tManagement").className = "menuItem";
  document.getElementById("tCommands").className = "menuItem";
  document.getElementById("tHelp").className = "menuItem";
  document.getElementById("tFeedback").className = "menuItem";
}

function DisplayMsgIfAny() {
  if (document.forms[0].err_flag.value == 1) {
    alert(document.forms[0].err_msg.value);
  } else if (document.forms[0].result_flag.value == 1) {
    alert(document.forms[0].cmd_result.value);
  }
  document.forms[0].err_flag.value = 0;
  document.forms[0].result_flag.value = 0;
  document.forms[0].buttonClicked.value = 0;
}

//need to get image for the OEMS and change the logo image.
function getLogoImage() {}
A {
  TEXT-DECORATION: none
}

#home_icon {
  height: 12px;
}

A:link {
  COLOR: #ffffff;
  TEXT-DECORATION: none
}

A:hover {
  COLOR: #ffffff;
  TEXT-DECORATION: none
}

A:active {
  COLOR: #000000;
  TEXT-DECORATION: none
}

A:visited {
  COLOR: #ffffff;
  TEXT-DECORATION: none
}

A.command {
  COLOR: #ffffff;
  TEXT-DECORATION: none
}

A.command:hover {
  COLOR: #ff9100;
  TEXT-DECORATION: underline
}

P {
  FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}

TD {
  FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}

P {
  FONT-SIZE: 11px;
  MARGIN: 0px;
  COLOR: #333366
}

TD {
  FONT-SIZE: 12px
}

TD.menuItem {
  PADDING-RIGHT: 10px;
  PADDING-LEFT: 10px;
  PADDING-BOTTOM: 4px;
  PADDING-TOP: 5px;
  BORDER-BOTTOM: #000000 5px solid;
  width: 1%;
  white-space: nowrap;
}

TD.selected {
  PADDING-RIGHT: 10px;
  PADDING-LEFT: 10px;
  PADDING-BOTTOM: 4px;
  COLOR: #000000;
  PADDING-TOP: 5px;
  BORDER-BOTTOM: #ff9100 5px solid;
  width: 1%;
  white-space: nowrap;
}

TD.space {
  WIDTH: 50%;
}

.style2 {
  COLOR: #ffffff
}
<script language="JavaScript" src="../servicescript41.js"></script>

<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onload="updatePage(); DisplayMsgIfAny();">
  <table width="100%" height="53" border="0" cellpadding="0" cellspacing="0">
    <tbody>
      <tr>
        <td style="PADDING-BOTTOM: 4px" align="middle" background="../images/background_web41.jpg" width="180">
          <img src="../images/cisco/cisco-logo-2007.gif" width="67" height="40" alt="logo" />
        </td>
        <td valign="bottom" background="../images/background_web41.jpg">
          <table border="0" cellspacing="0" cellpadding="0" width="100%">
            <tbody>
              <tr>
                <td class="menuItem" id="tMonitor" style=""><a href="frameMonitor.html" id="cMonitor" accesskey="M" onmouseover="highlight('Monitor')" onmouseout="removeHighlight('Monitor')" onclick="selectTab('Monitor')" onfocus="highlight('Monitor')" onblur="removeHighlight('Monitor')" target="mainFrame"><u>M</u>ONITOR</a></td>
                <td class="selected" id="tWlans" style=""><a href="frameWlan.html" id="cWlans" accesskey="W" onmouseover="highlight('Wlans')" onmouseout="removeHighlight('Wlans')" onclick="selectTab('Wlans')" onfocus="highlight('Wlans')" onblur="removeHighlight('Wlans')" target="mainFrame"><u>W</u>LANs</a></td>
                <td class="menuItem" id="tSwitch" style=""><a href="frameSwitching.html" id="cSwitch" accesskey="C" onmouseover="highlight('Switch')" onmouseout="removeHighlight('Switch')" onclick="selectTab('Switch')" onfocus="highlight('Switch')" onblur="removeHighlight('Switch')" target="mainFrame"><u>C</u>ONTROLLER</a></td>
                <td class="menuItem" id="tWireless" style=""><a href="frameWireless.html" id="cWireless" accesskey="I" onmouseover="highlight('Wireless')" onmouseout="removeHighlight('Wireless')" onclick="selectTab('Wireless')" onfocus="highlight('Wireless')" onblur="removeHighlight('Wireless')" target="mainFrame">W<u>I</u>RELESS</a></td>
                <td class="menuItem" id="tSecurity" style=""><a href="frameSecurity.html" id="cSecurity" accesskey="S" onmouseover="highlight('Security')" onmouseout="removeHighlight('Security')" onclick="selectTab('Security')" onfocus="highlight('Security')" onblur="removeHighlight('Security')" target="mainFrame"><u>S</u>ECURITY</a></td>
                <td class="menuItem" id="tManagement" style=""><a href="frameManagement.html" id="cManagement" accesskey="A" onmouseover="highlight('Management')" onmouseout="removeHighlight('Management')" onclick="selectTab('Management')" onfocus="highlight('Management')" onblur="removeHighlight('Management')" target="mainFrame">M<u>A</u>NAGEMENT</a></td>
                <td class="menuItem" id="tCommands" style=""><a href="frameCommands.html" id="cCommands" accesskey="O" onmouseover="highlight('Commands')" onmouseout="removeHighlight('Commands')" onclick="selectTab('Commands')" onfocus="highlight('Commands')" onblur="removeHighlight('Commands')" target="mainFrame">C<u>O</u>MMANDS</a></td>
                <td class="menuItem" id="tHelp"><a href="javascript:helpAction()" id="cHelp" accesskey="L" onmouseover="highlight('Help')" onmouseout="removeHighlight('Help')" onfocus="highlight('Help')" onblur="removeHighlight('Help')">HE<u>L</u>P</a></td>
                <td class="menuItem" id="tFeedback" style=""><a href="javascript:feedbackAction()" accesskey="F" onmouseover="highlight('Feedback')" onmouseout="removeHighlight('Feedback')" onfocus="highlight('Feedback')" onblur="removeHighlight('Feedback')"><u>F</u>EEDBACK</a></td>
                <td class="space">&nbsp;</td>
              </tr>
            </tbody>
          </table>
        </td>
      </tr>
    </tbody>
  </table>
  <div style="position:absolute; right:0px; top:0px; margin: 3px 10px 0px 0px">
    <p><a href="#" onclick="javascript:saveConfigAction()" accesskey="v" class="command">Sa<u>v</u>e Configuration</a> &nbsp;|&nbsp; <a href="#" onclick="javascript:pingAction();" accesskey="p" class="command"><u>P</u>ing</a> &nbsp;|&nbsp; <a class="command" href="#" accesskey="g" onclick="javascript:logoutAction();">Lo<u>g</u>out</a>&nbsp;|&nbsp;<a href="#" onclick="javascript:contentframe_screen_refresh()" accesskey="r" class="command"><u>R</u>efresh</a></p>
  </div>
  <form method="post" action="/screens/banner.html">
    <input type="hidden" name="access_control" size="16" maxlength="15" value="1">
    <input name="hSelectedTab" type="hidden" id="hSelectedTab" value="Wlans">
    <input type="hidden" name="err_flag" size="16" maxlength="15" value="0">
    <input type="hidden" name="err_msg" size="512" maxlength="511" value="">
    <input type="hidden" name="result_flag" size="16" maxlength="15" value="0">
    <input type="hidden" name="cmd_result" size="512" maxlength="511" value="Config Saved">
    <input type="hidden" name="ping_address" size="50" maxlength="50" value="">
    <input type="hidden" name="interfaceType" size="11" maxlength="11" value="">
    <input type="hidden" name="buttonClicked" size="16" maxlength="15" value="0">
  </form>
</body>

编辑 2: 来自 Node.js 的错误消息:

        NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[id="cWlans"]"}
          (Session info: chrome=61.0.3163.100)
          (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
            at WebDriverError (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:27:5)
            at NoSuchElementError (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:192:5)
            at Object.checkLegacyResponse (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:546:15)
            at parseHttpResponse (C:\Selenium\node_modules\selenium-webdriver\lib\http.js:509:13)
            at doSend.then.response (C:\Selenium\node_modules\selenium-webdriver\lib\http.js:441:30)
            at process._tickCallback (internal/process/next_tick.js:109:7)
        From: Task: WebDriver.findElement(By(css selector, *[id="cWlans"]))
            at thenableWebDriverProxy.schedule (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:807:17)
            at thenableWebDriverProxy.findElement (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:1014:17)
            at siteNavigate (C:\Selenium\byot.js:29:8)
            at sleep.then (C:\Selenium\byot.js:21:5)
        From: Task: WebElement.click()
            at thenableWebDriverProxy.schedule (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:807:17)
            at WebElementPromise.schedule_ (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:2010:25)
            at WebElementPromise.click (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:2092:17)
            at siteNavigate (C:\Selenium\byot.js:29:37)
            at sleep.then (C:\Selenium\byot.js:21:5)

【问题讨论】:

  • 你确定dom元素在选择元素之前已经加载了吗?
  • 如果可能的话,你能分享一下html链接吗?
  • 我注意到您的链接元素中有 target="mainFrame",您的页面是否有框架/iframe,如果有,请先切换到框架,然后再从框架中进行任何操作。
  • @yong,你明白了。我现在发布一个关于我发现的答案。谢谢!

标签: javascript google-chrome selenium


【解决方案1】:

好的,我提前道歉。最初我没有意识到该页面在页面内嵌套了几个 iframe。长话短说,框架最终一直是问题所在。该站点设置了四个框架,其中一些框架根据上下文而变化,而一些框架在初始登录后基本上保持不变。最困难的部分是知道要切换到哪个框架,并跟踪我当前关注的上下文。 这是我最终得到的结果:

const {Builder, By, until} = require('selenium-webdriver');
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();


driver.get('http://sitetonavigate.com');
driver.manage().window().maximize();
driver.findElement(By.name('bSubmit ')).click();        

function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

// Wait until Chrome is fully loaded to launch AutoIT login script
sleep(4500).then(() => {
    autoIT();
});

function autoIT() {
    var child_process = require('child_process');
    var workerProcess = child_process.execFile("C:\\Selenium\\autoITscript.exe");
    sleep(2500).then(() => {
        siteNavigate();
    });
}

function siteNavigate() {
    driver.switchTo().frame("banner");
    driver.findElement(By.id('cWlans')).click();

    //Select correct WLAN
    sleep(2500).then(() => {
        driver.switchTo().defaultContent();
        driver.switchTo().frame("mainFrame");
        driver.switchTo().frame("content"); 
        driver.findElement(By.xpath('/html/body/form/table[3]/tbody/tr[8]/td[2]/input')).click();
    });
}               

【讨论】:

  • 很高兴它有帮助。
【解决方案2】:

你可以使用:

元素1:

 driver.findElement(By.id('tWlans')).click(); 

元素2:

 driver.findElement(By.name('1.6.7.wlan_id')).click();

【讨论】:

  • 对,这也是我的第一个想法。它不起作用;我只是收到“无法找到元素”的错误。
  • 好吧,那么可能有多个元素具有相同的 id 和/或名称。
  • 据我所知,没有其他元素具有相同的名称/id。
  • @drummingrocks,给我们整个页面 (HTML)。
  • 对于第二个元素,我建议使用 CSS 选择器来查找元素。
【解决方案3】:

您正在点击 TD,因为它的 ID 为tWlans。您(大概)想要单击其中包含的A 标签。我建议使用 CSS 选择器 #tWlans &gt; a。代码如下。我添加了等待,但可能需要也可能不需要。

WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#tWlans > a"))).click();

至于第二个元素,它不在您发布的完整 HTML 中,所以我不确定它是否独特,但您可以尝试以下几个 CSS 选择器:

input[name='1.6.7.wlan_id']
input[onlick^='editThisWlan']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2012-04-09
    • 2023-02-24
    • 1970-01-01
    相关资源
    最近更新 更多