无法单击元素,但 css 和 xpath 都是验证路径



我无法单击此元素,请尝试CSS选择器和Xpaths。任何人都可以帮忙,不断得到无效的选择器,XPath/无法找到元素。然而,当我使用检查器验证这些元素是否正确时,为什么我的 Web 驱动程序脚本找不到它们?

.HTML:

<div class="ap-ba-well-button"> 
<!-- ngIf: service.booking_status_type !== 'Not Bookable Online' -->
<button ng-if="service.booking_status_type !== 'Not Bookable Online'" class="ap-button ng-binding ng-scope">Book</button>
<!-- end ngIf: service.booking_status_type !== 'Not Bookable Online' --> 
<!-- ngIf: service.booking_status_type === 'Not Bookable Online' --> 
</div>

代码试用:

driver.find_element(By.CSS_SELECTOR, ".ap-popover-well-group-single:nth-child(1) .ap-button").click()
driver.find_element_by_xpath(“//?/button[@innertext='Book']”) 
driver.find_element_by_xpath(“/html//span[@class='ng-scope']/ap-booking-app[@class='ng-scope']/div[@class='ap-ba-wrapper ng-scope']/div[@class='ap-ba-container with-footer']//ap-booking-app-step-services[@data='data']/div/div[1]//div[@class='ap-ba-well-single ng-scope']//button[@class='ap-button ng-binding ng-scope']”)

任何帮助都会很棒

问题是,当您想要单击时,即使您提供了正确的路径,网页中也不存在所需的元素。

我解决这个问题的方法是这样的:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as E
clickButton = WebDriverWait(browser,5).until(EC.element_to_be_clickable((By.XPATH, "ID")))

诱导WebDriverWait(( 和element_to_be_clickable(( 并遵循 Xpath 选项。

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//button[text()='Book']"))).click()

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//button[@class='ap-button ng-binding ng-scope' and text()='Book']"))).click()

您需要导入以下库。

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

从您提供的 HTML 和您的代码试用中,很明显该元素是一个 Angular 元素,因此您必须诱导WebDriverWaitelementToBeClickable()并使用以下定位器策略:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ap-ba-well-button button.ap-button.ng-binding.ng-scope"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='ap-ba-well-button']//button[@class='ap-button ng-binding ng-scope' and text()='Book']"))).click()
    
  • 注意:您必须添加以下导入:

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

最新更新