英文:
Python Selenium: Click element by custom attributes
问题
我正在尝试使用Selenium点击这个按钮:
<button class="MuiButtonBase-root MuiButton-root jss38 MuiButton-contained MuiButton-containedPrimary" tabindex="0" type="button" data-test="unifiedCrazyButton"><span class="MuiButton-label">让我们疯狂一下</span><span class="MuiTouchRipple-root"></span></button>
我无法通过类名来做到这一点,因为有其他具有相同类名的按钮,而且这个格式的xpath值:
/html/body/div[10]/div[3]/div/div[3]/button[2]
会不断变化,这很不幸。
唯一可识别的因素似乎是:
data-test="unifiedCrazyButton"
如何使用Selenium点击这个按钮?
英文:
I am trying to click this button with Selenium:
<button class="MuiButtonBase-root MuiButton-root jss38 MuiButton-contained MuiButton-containedPrimary" tabindex="0" type="button" data-test="unifiedCrazyButton"><span class="MuiButton-label">Let's get crazy</span><span class="MuiTouchRipple-root"></span></button>
I can't do it by the class name, because there are other buttons with the same class name, and also the xpath value in this format:
/html/body/div[10]/div[3]/div/div[3]/button[2]
keeps changing which is unfortunate.
The only identifying factor seems to be
data-test="unifiedCrazyButton"
How can I click this button with Selenium?
答案1
得分: 0
请注意:您需要添加以下导入:
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()
方法),并且您可以使用以下任一定位策略:
- 使用_CSS_SELECTOR_:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-test='unifiedCrazyButton'] span.MuiButton-label"))).click()
- 使用_XPATH_:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@data-test='unifiedCrazyButton']//span[@class='MuiButton-label' and contains(., 'get crazy')]"))).click()
这将点击所需的元素。
英文:
The desired element is a dynamic element, so to click on the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
-
Using CSS_SELECTOR:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-test='unifiedCrazyButton'] span.MuiButton-label"))).click()
-
Using XPATH:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@data-test='unifiedCrazyButton']//span[@class='MuiButton-label' and contains(., 'get crazy')]"))).click()
-
Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论