简体   繁体   中英

How to find a website element by id using Selenium python?

I'm trying to create a script that should download a given episode . For example, I want to open the magnet of episode 6 in 720p. However, Selenium doesn't find the element even though the id is correct.

I first tried using Xpath , but I get the same error.

Attempt

def downloadEpisode(episode):
    if episode > 9:
        id = str(episode)
    else:
        id = "0" + str(episode)
    #xpath = "//*[@id='" + id + "-720p']/span[2]/a" copied it using element inspect
    driver = webdriver.Chrome()
    driver.get("https://horriblesubs.info/shows/black-clover/")

    element1=WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID, id)))

    #also tried these two below
    #element1 = driver.find_element_by_id(id)
    #element1 = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,xpath)))

    element2 = element1.find_element_by_id(id + "-720p")
    element3 = element2.find_element_by_link_text("magnet")

    actions = ActionChains(driver)
    actions.click(element3).perform()

How do I solve this problem?

It sounds like your encountering a very common, but completely resolvable issue. You first need to scroll into view (like scrolling down a page) before attempting to perform the click action on the element, so it then becomes visible to the DOM. Either with actionchains or execute_script.

actions.move_to_element(element).perform()

This older post should make things a little clearer buddy :) Scrolling to element using webdriver?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM