【问题标题】:Invalid selector: Compound class names not permitted error using Selenium无效的选择器:不允许使用 Selenium 的复合类名称错误
【发布时间】:2019-04-30 20:52:55
【问题描述】:

我正在尝试通过 webWhatsapp 从聊天中打印我的一条消息。

我可以通过控制台选项卡中的 Javascript 做到这一点,我是这样做的

recived_msg = document.getElementsByClassName('XELVh selectable-text invisible-space copyable-text') // returns an array of the chat
recived_msg[5].innerText // shows me the 4th message content

问题是我试图在 python 上做同样的事情,但它对我不起作用..

这是我尝试过的:

from selenium import webdriver
recived_msg = driver.find_element_by_class_name('XELVh selectable-text invisible-space copyable-text')
final = recived_msg[5].innerText #doesnt work for some reason

我得到的错误是:消息:无效选择器:不允许复合类名

我对 javascript 有点陌生,很抱歉造成误解,感谢您的帮助! :)

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver xpath css-selectors


    【解决方案1】:

    根据selenium.webdriver.common.by实现的文档:

    class selenium.webdriver.common.by.By
        Set of supported locator strategies.
    
        CLASS_NAME = 'class name'
    

    所以,

    • 使用find_element_by_class_name() 您将无法传递多个类名。 传递多个类,您将面临以下错误:

      Message: invalid selector: Compound class names not permitted
      
    • 此外,由于您要返回聊天数组,因此您需要使用 find_elements*

    • 而不是 find_element*

    解决方案

    作为替代方案,您可以使用以下任一Locator Strategies

    • CSS_SELECTOR:

      recived_msg = driver.find_elements_by_css_selector(".XELVh.selectable-text.invisible-space.copyable-text")
      
    • XPATH:

      recived_msg = driver.find_elements_by_xpath("//*[@class='XELVh selectable-text invisible-space copyable-text']")
      

    【讨论】:

    • 非常感谢!,我不确定这些,这对我很有帮助:)
    【解决方案2】:

    按照 herehere too 的建议使用 css 选择器

    recived_msg = driver.find_element_by_css_selector('XELVh.selectable-text.invisible-space.copyable-text')
    

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2023-03-29
      • 2015-11-09
      • 2020-11-04
      • 1970-01-01
      相关资源
      最近更新 更多