Python Selenium有时单击,有时不单击

2024-10-06 11:46:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python和Selenium在PredictIt上打开不同的页面。到目前为止,我有:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


chrome_options = Options()
chrome_options.add_argument("--disable-notifications")
browser = webdriver.Chrome(options = chrome_options)
browser.get('https://www.predictit.org/account/')

#Input username into PredictIt
username = browser.find_element_by_id("username")
username.clear()
username.send_keys([MY USERNAME])

#Input password into PredictIt
password = browser.find_element_by_id("password")
password.clear()
password.send_keys([MY PASSWORD])

#Click login button
browser.find_element_by_xpath('//*[@id="app"]/div[3]/div/div/div/div[2]/div/form/div/div[6]/button[@type="submit"]').click()
browser.get_cookies()          #get_cookies() allows it to stay logged in
browser.find_element_by_xpath('//*[@id="nav-markets"]').click()

最后一行代码将其路由到“市场”页面。我的问题是,这有时有效,有时无效。我会说,大约60%的时间,它点击通过并把我带到页面。其余40%的时间,在登录后会停留在当前页面上,并产生错误:

selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <a href="/markets" class="main-nav__link" id="nav-markets">...</a> is not clickable at point (270, 24). Other element would receive the click: <div class="modal__wrapper">...</div>
  (Session info: chrome=86.0.4240.198)

有人能解决为什么会这样吗


Tags: divbrowseridbyseleniumusernamepassword页面
2条回答

在您登录后,我会引导webdriver等待元素弹出,因为元素可能无法加载或当前无法交互

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

WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='nav-markets']"))).click()

我猜这是因为代码中没有延迟,所以所有内容都同时追加。在提交表单之后,您可能需要添加一些延迟,以便页面可以加载。 根据经验,我总是在提交表单或使用time.sleep()加载页面等操作之前添加一些延迟,0.5s应该足够了

导入time模块并尝试在最后一行之前添加time.sleep(0.5)

相关问题 更多 >