如何通过 Selenium WebDriver 和 Python 定位用户名和密码元素

Posted

技术标签:

【中文标题】如何通过 Selenium WebDriver 和 Python 定位用户名和密码元素【英文标题】:How to locate the username and password element through Selenium WebDriver and Python 【发布时间】:2019-06-02 07:17:37 【问题描述】:

我正在尝试使用 Selenium 自动输入特定网站的用户名和密码。我无法找到将密钥发送到的元素。我在下面附上了网站的 html 代码。

这是我目前使用的:

username = driver.find_element_by_id('UserName').getAttribute('value')

此外,该网站以 .bsd 结尾,我并不完全熟悉,并认为它可能会导致问题。

谢谢。

<html>
        <head> 
          <meta http-equiv="content-type" content="text/html; charset=utf-8">
          <link rel="stylesheet" href="css/general.css" type="text/css">                 
          <title>RC Inspection - Risk Control</title>
          <script language="javascript1.3" src="scripts/clientside/badgerAPI.js"></script>
          <script language="javascript1.3" src="scripts/clientside/inspectionClient.js"></script>
          <script language="javascript1.3" src="scripts/clientside/validate.js"></script>
          <script language="javascript1.3" src="scripts/widJETs/JETClient.js"></script>
          <script language="javascript1.3" src="scripts/widJETs/JETDataTable.js"></script>
          <script>var searchParameters;</script>
        </head>     
        <frameset rows="0,95,*" framespacing="0">
 
          <frame name="SystemWin" src="about:blank" bgcolor="#FFFFFF" margin margin frameborder="0" framespacing="0" scrolling="auto">
          <frame name="HeaderWin" src="about:blank" bgcolor="#FFFFFF" margin margin frameborder="0" framespacing="0" scrolling="no">
          <frame name="MainWin" src="Logon.bsd?Lang=English'" margin margin frameborder="0" framespacing="0" scrolling="auto"
<html><head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <script language="javascript1.3" src="scripts/clientside/XHConn.js"></script>
        
        <link rel="stylesheet" href="css/logon.css" type="text/css">  
        
        <script language="javascript1.3">
 
          function executeAction(sFunction)

            if (sFunction=='OnLoad')   
                this.document.MainForm.UserName.focus();
                hide('r5');
            
            else if (sFunction=='Login')  
            
               fParms='UserName,T,50,1|Password,T,20,1';

               if(top.validatePage('top.MainWin.document.MainForm',fParms,'English'))
                 top.goPage('LogonUser@Logon.bsd?form=top.MainWin.document.MainForm|target=SystemWin|Lang=English') ;
             
            else if (sFunction=='ForgotPassword')  
               hide('r1');
               hide('r2');
               show('r5');
            
            else if (sFunction=='ResetPassword')  
        if(top.MainWin.document.MainForm.RP_UserName.value == "") 
          alert('Please enter Your Username');
          return false;
               
        var r = confirm("Are you sure you wish to reset your password?");
        if (r == true) 
          try 
              var myConn = new XHConn();
              if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
              myConn.connect("ResetPassword@Utilities.bsd", "POST", "RP_UserName="+this.document.MainForm.RP_UserName.value+"&Lang=English", fn_ChangeItem);
          
          catch(e) 
            var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
            alert("Unable to get XML data:\n" + msg);
            return;
          
        
             
        
  
              fn_ChangeItem = function (XML)      
                   eval(XML.responseText) ;
              
             hide=function (szDivID) 
               if(document.layers)    //NN4+
                 eval("document."+szDivID+".visibility = 'hide'");
               else if(document.getElementById)    //gecko(NN6) + IE 5+
                     
            var obj = document.getElementById(szDivID);
                      obj.style.display =  "none";
                   
               else if(document.all) // IE 4
                     document.all[szDivID].style.display =  "none";
                
             show=function (szDivID) 
               if(document.layers)    //NN4+
                    eval("document."+szDivID+".visibility = 'show'");
               else if(document.getElementById)    //gecko(NN6) + IE 5+
                   var obj = document.getElementById(szDivID);
                    obj.style.display =  "";
                
               else if(document.all) // IE 4
                   document.all[szDivID].style.display =  "";
                
        </script>
        </head>
        <body onload="javascript:executeAction('OnLoad');" margin margin>

        <div class="loginwrapper">
            
            <div class="logoncontent">
                <div id="logon_header">
          <img  border="0" src="./images/companylogo.gif">
          
          <div class="logintop">
            Risk Control System <br>
            version 4.5.4.1.5
          </div> 
                </div>
        <div class="clear">&nbsp;</div>
                <div id="logon_content">
          <form name="MainForm" enctype="multipart/form-data">
          
            <div id="r1">
              <div style="float:left;margin-right:20px;">
                <label for="UserName">User Name</label>
                <input type="text" id="UserName" name="UserName" maxlength="50" tabindex="1">
              </div>
              <div style="float:left;">
                <label for="Password">Password</label>
                <input type="password" id="Password" name="Password" maxlength="20" tabindex="2" onkeypress="if (event.keyCode=='13') executeAction('Login');">
              </div>
            </div>
            
            <div class="clear">&nbsp;</div>
            
            <div id="r2">
              <a class="small" href="javascript:void(0);" onclick="executeAction('ForgotPassword');return false;">Forgot Password?</a>
              <span class="action_button green_button"><a href="javascript:void(0);" tabindex="3" onclick="executeAction('Login');">Login</a></span>
            </div>
            
            <div id="r5" style="display: none;">
              <label class="rp_label" for="RP_UserName">Please Enter Your Username</label>
              <input type="text" name="RP_UserName" value="" size="30" maxlength="50">&nbsp;&nbsp;
              <!-- <a href="javascript:void(0);" onclick="executeAction('ResetPassword');return false;">Reset Password</a> -->
              <input type="submit" value="Reset Password" onclick="executeAction('ResetPassword');return false;">
            </div>
          </form> 
        </div>
            </div>
              
      <div class="clear">&nbsp;</div>
      
      <div class="loginbottom">
        <a style="text-decoration: none;" href="http://www.riskcontroltech.com/" target="_blank">Risk Control Technologies Inc.</a> Copyright © 2015. All rights reserved.<br>
        All Trademarks are owned by their respective companies.            
      </div>                      
    </div><!-- end loginwrapper -->
        
      
      
    </body></html>
        </frameset>
   
     
     </html>

【问题讨论】:

使用 id 找到它。如果您需要有关如何帮助您的建议,请在您尝试解决问题的地方添加代码 +1 附截图不好的做法,社区成员不会输入html代码让你重现你的问题,你可以添加html snip代替图片 我已经添加了代码。 【参考方案1】:

只需使用WebDriverWait:

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

driver = webdriver.Chrome(executable_path=r'C:\path\To\chromedriver.exe')
driver.get(url)

wait = WebDriverWait(driver, 10)

username = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@id='UserName']")))

# username = driver.find_element_by_xpath("//input[@id='UserName']")
username.send_keys("the useName")

# password = driver.find_element_by_xpath("//input[@id='Password']")

password =wait.until(EC.presence_of_element_located((By.XPATH, "//input[@id='Password']")))
password.send_keys("yourPassword")

希望对您有所帮助!

【讨论】:

这是我最初尝试运行的,但我收到以下错误消息: NoSuchElementException: no such element: Unable to locate element: "method":"id","selector":"UserName" (会话信息: chrome=71.0.3578.98) (驱动程序信息: chromedriver=2.42.591088 (7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 10.0.15063 x86_64) @Its_code_outside 我已经更新到 xpath...现在试试 表示未定义名称“wait”。另外,非常感谢您提供的所有帮助。我真的很感激。 不用担心。不过它给了我 TimeoutException。【参考方案2】:

要将字符序列发送到特定网站中的 用户名密码 字段,因为元素位于 &lt;frame&gt; 内,您必须:

诱导 WebDriverWait 使所需的框架可用并切换到它。 诱导 WebDriverWait 使所需的元素可点击

您可以使用以下任一解决方案:

使用CSS_SELECTOR

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"frame[name='MainWin'][src^='Logon.bsd?Lang=English']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for='UserName']"))).send_keys("Its_code_outside")
driver.find_element_by_css_selector("label[for='Password']").send_keys("Its_code_outside")

使用XPATH

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//frame[@name='MainWin' and starts-with(@src, 'Logon.bsd?Lang=English')]")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='UserName']"))).send_keys("Its_code_outside")
driver.find_element_by_xpath("//label[@for='Password']").send_keys("Its_code_outside")

注意:您必须添加以下导入:

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

【讨论】:

我使用了这个并收到以下错误消息:WebDriverException: unknown error: cannot focus element. @Its_code_outside 对于哪个元素 UsernamePassword 它没有指定。 (这是第一次发生这种情况)通常它已指定用户名或密码作为错误源。 查看我更新的答案并告诉我状态 如果是本地 url 会有什么不同吗?

以上是关于如何通过 Selenium WebDriver 和 Python 定位用户名和密码元素的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 Selenium Webdriver 检索元素的 HTML?

如果我通过 Selenium Webdriver 和 Java 知道相应的文本,如何提取 DOM 元素的 ID 属性

JMeter如何联合Selenium WebDriver进行自动化测试?

如何使用 Selenium WebDriver、Java 通过文本选择 Web 元素

如何使用 selenium webdriver 发送 cookie?

如何使用 webdriver selenium 从标签中单击按钮