无效的选择器:不允许使用 Selenium 的复合类名称错误
Posted
技术标签:
【中文标题】无效的选择器:不允许使用 Selenium 的复合类名称错误【英文标题】:Invalid selector: Compound class names not permitted error using 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 有点陌生,很抱歉造成误解,感谢您的帮助! :)
【问题讨论】:
【参考方案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】:按照 here 和 here too 的建议使用 css 选择器
recived_msg = driver.find_element_by_css_selector('XELVh.selectable-text.invisible-space.copyable-text')
【讨论】:
以上是关于无效的选择器:不允许使用 Selenium 的复合类名称错误的主要内容,如果未能解决你的问题,请参考以下文章
如何解决硒循环中的这个错误? InvalidSelectorException:消息:无效选择器:无法使用 xpath 定位元素