Home > Net >  How can I make Selenium click on a href by css selector?
How can I make Selenium click on a href by css selector?

Time:03-19

I have been trying to make a Selenium bot that searches for a word on github, clicks on the first link and then downloads it with Python 3.8 and I got stuck with making the bot click on the hyperlink. I understand that I can make the bot click on it with driver.find_element(By.XPATH, "Xpath").click() but I want to be able to find the path of the href with another method for the sake of learning, in this case CSS_SELECTOR. Source code of the first hyperlink result is like this:

source code

Since every single result is under the same "a" selector with a class of "v-align-middle", I thought of using this code: driver.find_element(By.CSS_SELECTOR, ".v-align-middle").click() but it did not seem to work. What am I missing?

CodePudding user response:

The desired element is a dynamic element, so to click() on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.v-align-middle[href='/asdf-vm/asdf'][data-hydro-click][data-hydro-click-hmac]"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='v-align-middle' and @href='/asdf-vm/asdf'][@data-hydro-click and @data-hydro-click-hmac]"))).click()
    
  • 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
    
  • Related