How to locate an element with multiple class names?

后端 未结 2 680
感动是毒
感动是毒 2021-01-17 06:35

I\'m trying to click on the following element with the class name equals \"clean right\":

  • 2条回答
    •  遇见更好的自我
      2021-01-17 06:59

      The previous answer is partially incorrect. please check the source code at :

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

      You can use class_name for multiple classes , just need to replace space with '.'

      Example for using class with 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")
      

      Output:

      
      

      If you check the exception from the by_class_name:

      You can see that it is using css_class locator under the hood ( You can see it add . in frontautomatically)

      Another Working example:

      from selenium import webdriver
      
      import time
      
      from selenium.webdriver.support import expected_conditions as EC
      
      driver = webdriver.Chrome()
      driver.get("https://stackoverflow.com/questions/65579491/find-element-by-class-name-in-selenium-giving-error/65579606?noredirect=1#comment115946541_65579606")
      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"))
      

    提交回复
    热议问题