使用Selenium WebDriver

时间:2018-02-20 22:44:12

标签: python selenium webdriver nosuchelementexception

我正在尝试使用Selenium WebDriver在网页上选择名为cslLogin的链接。它位于一个名为topframe的子框架中,但即使我切换到其父框架TopLevelFrame,我也无法访问它,我可以成功完成。 html页面有这个基本布局:

<html>
 <head>...</head>
  <frameset name="ATopLevelFrameSet">
   <frame name="TopLevelFrame">
    #document
     <html>
      <head></head>
       <frameset name="Aframeset">
        <frame name="topframe">
         #document
          <html>
           <head>...</head>
           <body class="clsBgColor">
            <table id="tblTitle">
             <tbody>
              <tr class="clsBackYellow"">
               <td class="clsDeviceStatusLink">
                <a class="clsLogin" href="javascript:void(0);"
                onclick="javascript:fnnLoginClick();">Login</a> == $0
               etc...

我可以使用TopLevelFrame成功切换到self.driver.switch_to.frame("TopLevelFrame"),但我无法访问topframeclsLogin(我得到NoSuchFrameExceptionNoSuchElementException,分别地)

我已尝试find_element_by_namefind_element_by_xpathfind_element_by_link_textfind_element_by_css_selector,并且还使用了

try:
    element = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.NAME, "TopLevelFrame"))
            )
finally:
    self.driver.quit()

如果是时间/页面加载问题,但在页面加载后很长时间。

我从其他帖子中得知,在我可以访问该元素之前,我需要先切换到最近的帧,但当然这不起作用。有什么建议?提前谢谢。

3 个答案:

答案 0 :(得分:0)

你应该使用&#34; find_element_by_xpath&#34; 只需打开网站,按&#34; ctrl + shift + c&#34;并检查它你想要提取什么。 找到元素中的行,右键单击并复制xpath,粘贴到函数中。

例如,请考虑此页面来源:

<html>
 <body>
  <form id="loginForm">
   <input name="username" type="text" />
   <input name="password" type="password" />
   <input name="continue" type="submit" value="Login" />
   <input name="continue" type="button" value="Clear" />
  </form>
</body>
<html>

表单元素的位置如下:

login_form = driver.find_element_by_xpath("/html/body/form[1]")
login_form = driver.find_element_by_xpath("//form[1]")
login_form = driver.find_element_by_xpath("//form[@id='loginForm']")

有关详细信息,请查看http://selenium-python.readthedocs.io/locating-elements.html

答案 1 :(得分:0)

试试这个,因为你有嵌套的iframe,切换到TopLevelFrame,然后切换到topframe并执行你的find_element_ *调用

driver.switch_to.frame(driver.find_element_by_name('TopLevelFrame'))
driver.switch_to.frame(driver.find_element_by_name('topframe'))
driver.find_element_by_class_name('clsLogin').click()

让我知道这是否有效

答案 2 :(得分:0)

要首先点击链接 cslLogin ,您必须切换到 TopLevelFrame <frame>,然后转到 topframe <frame>然后单击链接,如下所示:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(By.NAME,"TopLevelFrame"))
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(By.NAME,"topframe"))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Login"))).click()
# Or
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//tr[@class='clsBackYellow']/td[@class='clsDeviceStatusLink']/a[@class='clsLogin']"))).click()