Python 为什么我不能在找到该元素后立即单击它,这取决于我在代码中尝试单击它的时间?
作为前言,我才刚刚开始使用python,对许多python特定的概念还没有掌握 我正在重构一些代码,试图隐藏获取selenium web元素的错误处理,在传递元素时遇到了一个奇怪的问题: selenium\u handler.py:Python 为什么我不能在找到该元素后立即单击它,这取决于我在代码中尝试单击它的时间?,python,selenium,web-applications,Python,Selenium,Web Applications,作为前言,我才刚刚开始使用python,对许多python特定的概念还没有掌握 我正在重构一些代码,试图隐藏获取selenium web元素的错误处理,在传递元素时遇到了一个奇怪的问题: selenium\u handler.py: import time from selenium.webdriver.chrome.webdriver import WebDriver import selenium def highlight(element): """Highlights (bl
import time
from selenium.webdriver.chrome.webdriver import WebDriver
import selenium
def highlight(element):
"""Highlights (blinks) a Selenium Webdriver element"""
driver = element._parent
def apply_style(s):
driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",
element, s)
original_style = element.get_attribute('style')
apply_style("background: yellow; border: 2px solid red;")
time.sleep(.3)
apply_style(original_style)
def find_element(driver: WebDriver, xpath: str, url: str = "", test: bool = True, max_timeout: int = -1,
max_attempts: int = -1, time_between_attempts: int = 0) -> selenium.webdriver.remote.webelement.WebElement:
if url:
driver.get(url)
start_time = time.time()
end_time = start_time + max_timeout
attempt_count = 0
element: selenium.webdriver.remote.webelement.WebElement
while time.time() < end_time if max_timeout >= 0 else True and \
attempt_count < max_attempts if max_attempts >= 0 else True:
attempt_count += 1
try:
element = driver.find_element_by_xpath(xpath)
if test:
print("highlighting")
highlight(element)
# element.click()
break
except:
time.sleep(time_between_attempts)
pass
# should only be past here if something went wrong so send error
element.click()
return element
raise Exception("could not get element")
from selenium import webdriver
from real_project import selenium_handler
import time
driver = webdriver.Chrome()
# -------------------------------Cape Coral----------------------
cape_coral_url = "https://capegis.maps.arcgis.com/apps/webappviewer/index.html?id=bbce9a471a534e7482d35716c4cb6f36"
time_for_elements_to_be_found = 5
def prepare_for_batch():
driver.refresh()
ok_button = selenium_handler.find_element(driver, url=cape_coral_url,
xpath="html/body/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/button",
# test=False,
max_timeout=time_for_elements_to_be_found)
print(type(ok_button))
while True:
try:
ok_button.click()
break
except:
pass
prepare_for_batch()
time.sleep(5)
driver.close()
我的错误显示在元素上。单击()。实际上,我将得到一个错误,即元素不可交互。但是如果我改为在try-catch块中使用element.click(),那么它将始终工作,没有问题。
如果我在一段时间内运行底部元素.click(),请尝试像第一个循环那样中断,然后它最终会单击
为什么会这样?它看起来不像是竞争条件,或者html仍在加载,或者类似的东西,否则第一个元素.click()将失败。我只是希望能够在代码中传递这些元素。谢谢
编辑:
忘记了实际调用此函数的代码可能您的代码运行得太快,浏览器仍需要一些时间来加载或滚动它以使其可单击。@furas但如果我在找到元素后立即调用click(),它会工作。如果我一直尝试在函数末尾单击,则它不起作用可能变量
元素中有不同的对象
-至少检查打印(元素)
-或者您加载了其他页面-元素
,如果加载了其他页面,它将不起作用。或者页面加载其他元素,而HTML树中的所有元素都在更改。@furas我创建了一个临时元素,并对它们进行了比较,它们是相同的元素。但这也不是问题,因为它们都会点击。问题是,如果我没有在循环中立即单击,我必须等待单击。