我无法单击此元素,尝试使用CSS选择器和Xpath。任何人都可以帮忙,继续获取无效的选择器,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")))
从您的代码试验中,很明显,该元素是Angular元素,因此您必须为elementToBeClickable()
引入WebDriverWait,然后为以下Locator Strategies:
使用CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".ap-popover-well-group-single:nth-child(1) .ap-button"))).click()
使用XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((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']"))).click()
注:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
产生WebDriverWait
()和element_to_be_clickable
()并遵循Xpath选项。
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//button[text()='Book']"))).click()
OR
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