Selenium和Chrome,无法选择元素

时间:2017-11-01 15:15:24

标签: javascript google-chrome selenium

我使用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();
}

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

编辑:

&#13;
&#13;
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() {}
&#13;
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
}
&#13;
<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>
&#13;
&#13;
&#13;

编辑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)

3 个答案:

答案 0 :(得分:1)

您可以使用:

元素1:

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

元素2:

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

答案 1 :(得分:1)

您点击了TD,因为它的ID为tWlans。您(可能)想要点击其中包含的A标记。我建议使用CSS选择器#tWlans > 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']

答案 2 :(得分: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();
    });
}