如何查找并单击包含多个 类 的按钮元素

How to find and click on a button element that contains multiple classes

使用python + selenium chromedriver。 在登录屏幕上并尝试单击登录按钮,但我似乎无法正确识别该元素。

代码试用:

login = driver.find_element_by_css_selector('tv-button.tv-button--no-border-radius.tv-button--size_large.tv-button--primary_ghost.tv-button--loader')
click(login)

HTML:

<button type="submit" class="tv-button tv-button--no-border-radius tv-button--size_large tv-button--primary_ghost tv-button--loader">
<span class="tv-button__text">Log In</span>
<span class="tv-button__loader"><span class="tv-button__loader-item"></span><span class="tv-button__loader-item"></span><span class="tv-button__loader-item"></span></span></button>

您似乎错过了开头的 .,因此 Css 选择器将寻找 tv-button 标签而不是 class。试试这个:

login = driver.find_element_by_css_selector('.tv-button.tv-button--no-border-radius.tv-button--size_large.tv-button--primary_ghost.tv-button--loader')
click(login)

毫无疑问,我们应该始终选择 css 选择器而不是 xpath。

但是您使用的 css 选择器 : .tv-button.tv-button--no-border-radius.tv-button--size_large.tv-button--primary_ghost.tv-button--loader 看起来很不稳定。

对于登录按钮,您可以使用:

xpath : //span[contains(text(),'Log In')]/parent::button

你应该避免使用 css 选择器的原因是(在这种情况下),css 选择器是 class 名称的组合,所以如果有 class 名称更改,您将不得不更改定位器。

在这种情况下更改 class 名称的可能性很大。因为它由 5 class 组成。

希望这会有所帮助。

我会尝试

的更短的 class 选择器
driver.find_element_by_css_selector('.tv-button').click()

尝试 Induce WebDriverWait 识别元素,然后单击它。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

element=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'button.tv-button span')))
print(element.text)
element.click()

该元素是一个动态元素,因此要定位并单击您必须为 element_to_be_clickable() 引入 WebDriverWait 的元素,您可以使用以下任一解决方案:

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.tv-button--no-border-radius.tv-button--loader>span.tv-button__text"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='tv-button tv-button--no-border-radius tv-button--size_large tv-button--primary_ghost tv-button--loader']/span[@class='tv-button__text' and text()='Log In']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC