如何使用 Selenium 和 Python 定位具有多个类名的元素

2024-01-04

我正在尝试单击类名称等于的以下元素"clean right":

<li class="clean right"></li>

我怎样才能通过使用找到它driver.find_element_by_class_name()


您不能将多个类名作为参数传递find_element_by_class_name()这样做你将面临如下错误:

invalid selector: Compound class names not permitted

有多种方法可以解决此用例,您可以使用以下任一方法定位策略 https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890:

  • 如果该元素只能通过classname clean您可以使用:

    driver.find_element_by_class_name("clean")
    
  • 如果该元素只能通过classname right您可以使用:

    driver.find_element_by_class_name("right")
    
  • 如果两者都classnames, clean and right必须识别元素,您可以使用CSS 选择器 /questions/tagged/css-selectors如下:

    driver.find_element_by_css_selector("li.clean.right")
    
  • 作为替代方案,您也可以使用xpath /questions/tagged/xpath如下:

    driver.find_element_by_xpath("//li[@class='clean right']")
    

tl; dr

无效的选择器:使用 Selenium 时不允许出现复合类名错误 https://stackoverflow.com/questions/53528072/invalid-selector-compound-class-names-not-permitted-error-using-selenium/53536022#53536022


参考

通过多个类名查找div元素? https://stackoverflow.com/questions/21713280/find-div-element-by-multiple-class-names/60515585#60515585

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Selenium 和 Python 定位具有多个类名的元素 的相关文章

随机推荐