【问题标题】:ElementNotInteractable Exception: Message: Element <a href=> could not be scrolled into viewElementNotInteractable 异常:消息:元素 <a href=> 无法滚动到视图中
【发布时间】:2020-03-24 18:33:32
【问题描述】:

我正在尝试在以下链接中单击并下载“Real Sector”: http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm

这是我尝试过的:

driver.get('http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm')
try:
    driver.find_element_by_css_selector("a[href= 'Chap-2.pdf']").click()

except NoSuchElementException:
    pass

但它给出了以下错误:

ElementNotInteractableException:消息:元素无法滚动到视图中

我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x selenium web-scraping


    【解决方案1】:

    您需要应用显式等待,等到页面上出现该元素,然后您可以点击它。
    您也可以先滚动到该元素,然后点击它。
    你可以这样做:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    driver.get('http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm')
    try:
        element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//a[@href='Chap-2.pdf']")))
        driver.execute_script("arguments[0].scrollIntoView();", element)
        element.click()
    
    except NoSuchElementException:
        pass
    

    您可以使用java脚本直接点击元素点击:

    driver.get('http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm')
    try:
        element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//a[@href='Chap-2.pdf']")))
        driver.execute_script("arguments[0].click();", element)
    
    except NoSuchElementException:
        pass
    

    【讨论】:

    • @Muhammadhassan 编辑了我的答案,请选择更新后的答案。
    • @Muhammadhassan 奇怪,因为它对我来说很好用。我添加了另一种点击元素的方法(使用 javascript 点击)。请检查并使用它,并请检查我在答案中提到的 xpath。
    • 谢谢,第二个解决方案按预期工作。但是,我仍然无法理解为什么第一个解决方案对您有效而对我无效。
    • @Muhammadhassan 可能是因为您打开的 chrome 的大小与我的不同,当您最大化 chrome 然后尝试单击元素时,它可能会起作用。
    【解决方案2】:

    尝试等待使用element_to_be_clickable

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href= 'Chap-2.pdf']")))
    element.click()
    

    【讨论】:

    • @Muhammadhassan 我已将代码更新为WebDriverWait,请重试
    【解决方案3】:

    点击"Real Sector"链接,引入WebDriverWait()element_to_be_clickable()并关注xpath选项。

    driver = webdriver.Chrome()
    driver.get('http://www.sbp.org.pk/reports/quarterly/fy19/Second/qtr-index-eng.htm')
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(.,'Real Sector')]"))).click()
    

    您需要导入以下库。

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

    浏览器快照点击后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-25
      • 2018-08-09
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      相关资源
      最近更新 更多