Search code examples
pythonselenium-webdriverxpathhref

using selenium xpath to click on href link, doesnt work


im trying to get the xpath of this, to click on the href link

<a href="/film/ah-fei-jing-juen/" class="frame has-menu" data-original-title="Days of Being Wild (1990)">

my code so far is

driver.find_element(By.XPATH, "/html/body/div[2]/div/div/section/ul/li[1]/div/div/a").click

and ive tried using find element by id as well. appreciate any help thanks!


Solution

  • Use this XPATH expression:

    (//ul[contains(@class,'poster-list -p70 -grid film-list clear')]//following::span[@class='overlay'])[1]
    

    Note: In the above expression, at the end [1] indicates first movie from top-left. If you want to locate second movie(element), just change that to [2] and so on.

    Full working code:

    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get("https://letterboxd.com/a2vre/films/by/rated-date/")
    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.XPATH, "(//ul[contains(@class,'poster-list -p70 -grid film-list clear')]//following::span[@class='overlay'])[1]"))).click()
    

    Imports:

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