Selenium+Python 定位一個偽元素的時候總是無法定位,連絕對定位都試過了,還是不行。
查了下可能是對應頁面的元素還沒加載完成,試着加了個顯示等待時間,果然獲取到了。
from selenium import webdriver import time from selenium.webdriver.support.ui import WebDriverWait driver = webdriver.Chrome() driver.get('https://XXXX.com/login') driver.find_element_by_id('account').clear() driver.find_element_by_id('account').send_keys('13120922896') driver.find_element_by_id('password').clear() driver.find_element_by_id('password').send_keys('KMtLcEbjfM') driver.find_element_by_xpath('//button[@class="ant-btn src-pages-login-index-module__login-button--9qwKk ant-btn-primary"]').click() wait = WebDriverWait(driver,5,0.5) wait.until(lambda driver: driver.find_element_by_xpath('//div[@class="src-pages-login-index-module__shop-card--brzB-"]/button[@class="ant-btn src-pages-login-index-module__choose-btn--1x6QG ant-btn-primary"]')) driver.find_element_by_xpath('//div[@class="src-pages-login-index-module__shop-card--brzB-"]/button[@class="ant-btn src-pages-login-index-module__choose-btn--1x6QG ant-btn-primary"]').click()
WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None)
timeout:最長超時時間,默認以秒為單位
poll_frequency:檢測的間隔時間,默認為0.5s
ignored_exceptions:超時后的異常信息,默認情況下拋出NoSuchElementException異常
until(method,message=''):調用該方法提供的驅動程序作為一個參數,直到返回值為True