为什么selenium不能识别Python中的类?

2024-07-04 08:58:10 发布

您现在位置:Python中文网/ 问答频道 /正文

Selenium没有识别该类。我试图在一个使用selenium的网站上点击一个音频按钮,但它无法识别这个类

class="jumbo--Z12Rgj4 buttonWrapper--x8uow audioBtn--1H6rCK"

这是我的密码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
options = webdriver.ChromeOptions() 
options.add_argument(r"user-data-dir=./c")

driver=webdriver.Chrome(executable_path=r"C:\Users\Users\Desktop\Scrapping\chromedriver.exe",options=options)
    
driver.get(r"https://www.xx------xx.com")
    
button5 = driver.find_element_by_class_name(r"jumbo--Z12Rgj4")
    
button5.click()

但是selenium抛出了一个异常

jumbo--Z12Rgj4

例外情况:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".label--Z12LMR3"}

Tags: fromimportdriverseleniumelementcommonselectorusers
3条回答

您希望目标的元素可能在每次加载时都有一个唯一的哈希类名,因为在网站上根本找不到它,所以与其使用类名,不如尝试使用它的xpath

若再次检查,将有多个类“jumbo Z12Rgj4”,因此selenium正在引发异常。 为了使其更具动态性,最好使用带有“contains(@class,'jumbo Z12Rgj4')的xpath,后跟另一个标识符以使搜索唯一

属性的值,即jumbo Z12Rgj4 buttonWrapper x8uow audioBtn 1H6rCK是动态的,每次访问应用程序时都会不断更改。要单击文本为“保存”的元素,可以使用以下任一Locator Strategies

  • 使用css_selector

    driver.find_element_by_css_selector("[class^='jumbo']").click()
    
  • 使用xpath

    driver.find_element_by_xpath("//*[starts-with(@class, 'jumbo')]").click()
    

理想情况下,要单击需要为element_to_be_clickable()诱导WebDriverWait的元素,可以使用以下Locator Strategies之一:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[class^='jumbo']"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[starts-with(@class, 'jumbo')]"))).click()
    
  • 注意:您必须添加以下导入:

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

相关问题 更多 >

    热门问题