Selenium定位重复类名元素:如何选择首个可点击按钮?
解决多类名元素的第一个定位问题
问题描述
我可以通过以下XPATH定位并点击"AKZEPTIEREN"按钮:
WebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.XPATH, '/html/body/div[4]/div/button[2]'))).click()
为实现更动态的定位,尝试使用类名定位,但代码如下:
WebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.CLASS_NAME, 'primary.accept.no-pop-execute'))).click()
页面上存在两个拥有primary accept no-pop-execute类名的元素,需要选择第一个元素。
解决方案
首先注意:By.CLASS_NAME不支持传入多个类名(空格分隔的是多个独立类,而非单个类名),所以原类名定位代码本身存在问题。可以通过以下几种方式正确定位第一个匹配元素:
方法1:使用XPATH定位第一个匹配元素
通过XPATH选取所有符合类名条件的元素,再取第一个:
# 精确匹配完整类名 WebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.XPATH, '(//button[@class="primary accept no-pop-execute"])[1]'))).click()
如果类名顺序可能变化,可改用包含匹配:
WebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.XPATH, '(//button[contains(@class, "primary") and contains(@class, "accept") and contains(@class, "no-pop-execute")])[1]'))).click()
方法2:使用CSS选择器定位第一个匹配元素
CSS选择器支持多类名组合,并可通过:first-of-type或:nth-child(1)指定第一个元素:
# 使用:first-of-type WebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, 'button.primary.accept.no-pop-execute:first-of-type'))).click() # 或使用:nth-child(1) WebDriverWait(driver, 15).until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, 'button.primary.accept.no-pop-execute:nth-child(1)'))).click()
内容的提问来源于stack exchange,提问作者MausHausi
相关产品推荐
相关产品推荐

