Python 如何查找并单击包含多个类的button元素

Python 如何查找并单击包含多个类的button元素,python,selenium,xpath,css-selectors,webdriverwait,Python,Selenium,Xpath,Css Selectors,Webdriverwait,使用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 ty

使用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按钮
标记,而不是类。试试这个:

login=driver.find_element_by_css_选择器('.tv button.tv button--no border radius.tv button--size_large.tv button--primary_ghost.tv button--loader'))
单击(登录)

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

但是您正在使用的css选择器:
.tv button.tv button--没有边框半径。tv button--size\u large.tv button--primary\u ghost.tv button--loader
看起来非常不稳定

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

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

您应该避免使用css选择器的原因是(在本例中),css选择器是类名的组合,所以如果任何类名发生更改,您必须更改定位器

在这种情况下很可能更改类名。因为它由5个等级组成


希望这会有所帮助。

我会尝试一个较短的类选择器

driver.find_element_by_css_selector('.tv-button').click()

尝试诱导
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()

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

  • 使用
    CSS\u选择器

    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
    

这基本上会监控按钮直到其可点击为止吗?这是否可以用于具有“提交”按钮的网页,该按钮在满足某些条件之前变灰,然后可单击?这是使用WebDriverWait的最佳做法。如果您的页面无法及时加载,则需要显式等待以检查元素是否可单击并等待指定时间。