WebDriverWait无法按预期工作 [英] WebDriverWait not working as expected
问题描述
我正在用硒来刮擦一些数据.
I am working with selenium to scrape some data.
我单击的页面上有一个按钮,说"custom_cols".此按钮为我打开一个窗口,从中可以选择列.
There is button on the page that I am clicking say "custom_cols". This button opens up a window for me where I can select my columns.
这个新窗口有时需要一些时间才能打开(大约5秒钟).因此,为了解决这个问题,我使用了
This new window sometimes takes some time to open (around 5 seconds). So to handle this I have used
WebDriverWait
,延迟为20秒.但是有时它无法在新窗口中选择查找元素,即使该元素是可见的也是如此.在其余时间中,这种情况只会发生十次一次.
with delay as 20 seconds. But some times it fails to select find elements on new window, even if the element is visible. This happens only once in ten times for rest of time it works properly.
我在其他地方也使用了相同的功能(WebDriverWait),并且可以正常使用.我的意思是,它要等到元素变得可见后,再在找到它时单击它.
I have used same function(WebDriverWait) on other places also and it is works as expected. I mean it waits till the elements gets visible and then clicks it at the moment it finds it.
我的问题是,即使我正在等待元素可见,为什么新窗口上的元素也不可见.要在此处添加,我尝试增加延迟时间,但有时还是会出现该错误.
My question is why elements on new window is not visible even though I am waiting for element to get visible. To add here I have tried to increase delay time but still I get that error once in a while.
我的代码在这里
def wait_for_elem_xpath(self, delay = None, xpath = ""):
if delay is None:
delay = self.delay
try:
myElem = WebDriverWait(self.browser, delay).until(EC.presence_of_element_located((By.XPATH , xpath)))
except TimeoutException:
print ("xpath: Loading took too much time!")
return myElem
select_all_performance = '//*[@id="mks"]/body/div[7]/div[2]/div/div/div/div/div[2]/div/div[2]/div[2]/div/div[1]/div[1]/section/header/div'
self.wait_for_elem_xpath(xpath = select_all_performance).click()
推荐答案
在等待元素并继续尝试调用click()
方法而不是使用presence_of_element_located()
方法时,需要使用 element_to_be_clickable()
如下:
Once you wait for the element and moving forward as you are trying to invoke click()
method instead of using presence_of_element_located()
method you need to use element_to_be_clickable()
as follows :
try:
myElem = WebDriverWait(self.browser, delay).until(EC.element_to_be_clickable((By.XPATH , xpath)))
更新
根据您在评论中的反问,以下是这三种方法的详细信息:
Update
As per your counter question in the comments here are the details of the three methods :