【问题标题】:Unable to click on link using python and selenium无法使用 python 和 selenium 点击链接
【发布时间】:2020-08-29 22:04:31
【问题描述】:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


# go to website
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(executable_path="chromedriver.exe", chrome_options=chrome_options)
action = webdriver.ActionChains(driver)
driver.get('https://www.clinicalkey.com/#!/browse/book/3-s2.0-C2016100010X')

# look for "login" and click
loginclick = driver.find_element_by_xpath("//*[@id='header']/div[3]/ol/li[3]/a/span").click()

为什么我在导航到给定的网站后无法点击右上角的登录部分?我收到一个错误:

Exception has occurred: NoSuchElementException
Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='header']/div[3]/ol/li[3]/a/span"}
  (Session info: chrome=85.0.4183.83)
  File "C:\python\download.py", line 18, in <module>
    loginclick = driver.find_element_by_xpath("//*[@id='header']/div[3]/ol/li[3]/a/span").click()

谢谢!

【问题讨论】:

    标签: python-3.x selenium selenium-chromedriver


    【解决方案1】:

    两个原因:

    1:等待元素加载

    2:由于元素在页面上不可见,请使用 java 脚本单击

    driver.get('https://www.clinicalkey.com/#!/browse/book/3-s2.0-C2016100010X')
    # look for "login" and click
    loginclick=WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, "//*[@id='header']/div[3]/ol/li[3]/a/span")))
    driver.execute_script("arguments[0].click();", loginclick)
    

    输出:

    【讨论】:

    • 太棒了!谢谢!你能解释一下这个 (driver.execute_script("arguments[0].click();") 是什么意思吗?
    • 由于您的元素隐藏在页面上,正常的 selenium python 绑定无法点击它。所以我们使用 Javascript 来定位元素并单击它。至于与网页元素交互,我们的普通脚本首先通过绑定转换为Javascript,然后按照指示执行操作。有时当它无法执行所需的操作时,我们可以使用直接 Javascript 来执行此操作。
    猜你喜欢
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 2016-09-26
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    相关资源
    最近更新 更多