带selenium的Python:无法使用id、xpath和selector访问元素,即使它是

2024-09-28 17:29:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要做的是单击弹出窗口中的“确定”按钮。“检查”菜单中提到的“确定”按钮如下: id="btn-confirm-yes"。使用此id访问元素,尝试复制其xpath并通过该id访问,并尝试通过div类访问。不幸的是,所有返回的元素都找不到。我很难理解为什么。你知道吗

 #This is the python script used to access 
 element = driver.find_element_by_id("btn-confirm-yes")  
 if element.is_displayed():  
   print "Confirm button element is there"
   driver.implicitly_wait(4) # seconds
   element.send_keys(Keys.RETURN)
 else:
   print "Confirm button element not found" 


 /* Hierarchy from Inspect menu */
 <div id="sing-out-confirm" class="reveal-modal small open" style="top: 100px; opacity: 1; visibility: visible; display: block;">
<h2 class="text-uppercase">ALL DEVICE SIGNOUT</h2>
<p>Click OK to confirm All Device Signout.</p>
<form id="sign-out-user-account-form" method="post" action="/portal-owner-web/user-account/sign-out-all-device">
    <div class="button-bar">
        <a class="button small close-reveal-modal mr5" href="#">Cancel</a>

        <a class="button small reveal-modal-button mr5" href="#" id="btn-confirm-yes">OK</a>
    </div>
</form>
</div

需要访问“检查”窗口中指定的元素: class="button small reveal-modal-button mr5" href="#" id="btn-confirm-yes"

朝着正确的方向轻推会很有帮助!你知道吗


Tags: divformid元素isbuttonelementout
2条回答
  1. 确保您试图检测的按钮不属于inline frame
  2. 在这种情况下,按钮可能不会立即在DOM中可用,例如,作为AJAX调用的结果,它被添加到主内容之后。因此,一个好的做法是使用Explicit Wait,以便让Selenium定期轮询DOM中的元素外观。你知道吗

参考代码:

element = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.ID, "btn-confirm-yes")))

您还需要添加以下import语句:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By

从HTML中可以很明显地看出,元素位于模态对话框中。因此,要click()OK按钮上,您必须诱导WebDriverWait,才能单击元素,并且可以使用以下Locator Strategies

  • 使用LINK_TEXT

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "OK"))).click()
    
  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.button.small.reveal-modal-button.mr5#btn-confirm-yes"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='button small reveal-modal-button mr5' and @id='btn-confirm-yes'][text()='OK']"))).click()
    
  • 注意:必须添加以下导入:

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

相关问题 更多 >