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

How to locate an element with multiple classnames using Selenium and Python

我正在尝试单击 class 名称等于 "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

有多种方法可以解决这个用例,您可以使用以下任一方法 :

  • 如果元素只能通过classnameclean来唯一标识可以使用:

    driver.find_element_by_class_name("clean")
    
  • 如果元素只能通过classnameright来唯一标识可以使用:

    driver.find_element_by_class_name("right")
    
  • 如果classnamescleanright是必须要标识的元素,可以使用如下:

    driver.find_element_by_css_selector("li.clean.right")
    
  • 作为替代方案,您还可以使用 ,如下所示:

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

tl;博士


参考

Find div element by multiple class names?

之前的回答部分不正确。请在 :

查看源代码

https://github.com/SeleniumHQ/selenium/blob/9160de55af9cc230f758f4ce6a2af8d1570f0614/py/selenium/webdriver/remote/webdriver.py

您可以对多个 class 使用 class_name,只需要将 space 替换为 '.'

使用 class 和 space 的示例:

from selenium import webdriver
from time import sleep

options = webdriver.ChromeOptions()
#options.headless = True
options.add_argument("--window-size=1920,1080")
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument(
    "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")
browser = webdriver.Chrome(options=options)
browser.get("https://www.instagram.com")
sleep(5)
#browser.refresh()
elem=browser.find_element_by_class_name('RP4i1.UVauz')
print(elem.get_attribute("outerHTML"))
browser.get_screenshot_as_file(f"screenshot.png")

输出:

<img class="RP4i1  UVauz" src="/static/images/homepage/screenshot1.jpg/d6bf0c928b5a.jpg" alt="">

如果你检查异常来自_class_name:

你可以看到它正在使用 css_class 定位器(你可以看到它自动在前面添加 .)

另一个工作示例:

from selenium import webdriver

import time

from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("
time.sleep(5)
elem = driver.find_element_by_class_name('overflow-x-auto.ml-auto.-secondary.grid.ai-center.list-reset.h100')

print(elem.get_attribute("outerHTML"))