我有一个动态变化的xpath元素,我喜欢单击它,我该怎么做?
//*[@id="/api/services/61_ellipsis"]
按钮HTML为:
<button type="button" class="v-btn v-btn--flat v-btn--icon v-btn--round theme--light v-size--default" id="/api/services/33_ellipsis">
<span class="v-btn__content">
<i aria-hidden="true" class="v-icon notranslate mdi mdi-dots-vertical theme--light">
</i>
</span>
</button>
如果ID动态变化,则不能使用确切的ID来获取元素,但是contains
查询可能有效
查询ID中包含api/services
的任何元素:
//*[contains(@id, 'api/services')]
在按钮上查询,没有任何ID信息。具有内部span
和i
元素:
//button[span/i]
查询ID中包含api/services
,并且还具有内部span
和i
元素的按钮元素:
//button[span/i and contains(@id, 'api/services')]
要保存ID,您要先找到元素,然后获取其ID属性:
buttonId = driver.find_element_by_xpath("//button[span/i and contains(@id, 'api/services')]").get_attribute("id")
所需的元素是动态元素,因此对于元素上的click()
,您必须为element_to_be_clickable()
引入WebDriverWait,并且可以使用以下任一解决方案:
使用CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.v-btn.v-btn--flat.v-btn--icon.v-btn--round.theme--light.v-size--default[id^='/api/services/'] > span.v-btn__content > i.v-icon.notranslate.mdi.mdi-dots-vertical.theme--light"))).click()
使用XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='v-btn v-btn--flat v-btn--icon v-btn--round theme--light v-size--default' and starts-with(@id, '/api/services/')]/span[@class='v-btn__content']/i[@class='v-icon notranslate mdi mdi-dots-vertical theme--light']"))).click()
注:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC