How to locate element by class name and specific a

2020-08-09 04:19发布

问题:

I'm using selenim python,and want to locate the following element:

<div id="coption5" class="copt" style="display: block;">

I need both the class name 'copt' and style value "display: block;",is there any way I can locate this element with both class name and attribute value at the same time?

Thanks!

回答1:

Incase considering the style value display: block; is mandatory you can induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.copt[id^='coption']")))
    
  • Using XPATH:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='copt' and starts-with(@id, 'coption')]")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC