简体   繁体   English

如何使用Selenium python通过id查找网站元素?

[英]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.例如,我想以 720p 打开第 6 集的磁铁。 However, Selenium doesn't find the element even though the id is correct.但是,即使id正确, Selenium也找不到该元素。

I first tried using Xpath , but I get the same error.我第一次尝试使用Xpath ,但我遇到了同样的错误。

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.在尝试对元素执行单击操作之前,您首先需要滚动到视图中(例如向下滚动页面),以便它对 DOM 可见。 Either with actionchains or execute_script.使用 actionchains 或 execute_script。

actions.move_to_element(element).perform()

This older post should make things a little clearer buddy :) Scrolling to element using webdriver?这篇较旧的帖子应该让事情变得更清楚一些:) 使用 webdriver 滚动到元素?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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