提问人:Rao Sahab 提问时间:4/11/2018 最后编辑:undetected SeleniumRao Sahab 更新时间:11/19/2019 访问量:17917
WebDriverWait 未按预期工作
WebDriverWait not working as expected
问:
我正在使用 selenium 来抓取一些数据。
我单击的页面上有一个按钮,上面写着“custom_cols”。此按钮为我打开了一个窗口,我可以在其中选择我的列。
这个新窗口有时需要一些时间才能打开(大约 5 秒)。所以为了处理这个问题,我使用了
WebDriverWait
延迟为 20 秒。但有时它无法选择在新窗口中查找元素,即使该元素可见。在其余时间里,这种情况每十次才会发生一次,它工作正常。
我在其他地方也使用了相同的功能(WebDriverWait),并且按预期工作。我的意思是它会等到元素变得可见,然后在找到它的那一刻单击它。
我的问题是,即使我正在等待元素可见,为什么新窗口上的元素不可见。在这里补充一点,我试图增加延迟时间,但我仍然偶尔会遇到这个错误。
我的代码在这里
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()
答:
14赞
undetected Selenium
4/11/2018
#1
一旦你等待元素并继续尝试调用方法而不是使用方法,你需要使用 element_to_be_clickable(),
如下所示:click()
presence_of_element_located()
try:
myElem = WebDriverWait(self.browser, delay).until(EC.element_to_be_clickable((By.XPATH , xpath)))
更新
根据您在评论中提出的反问题,以下是三种方法的详细信息:
presence_of_element_located
presence_of_element_located(定位器)定义如下:
class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator)
Parameter : locator - used to find the element returns the WebElement once it is located
Description : An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible or interactable (i.e. clickable).
visibility_of_element_located
visibility_of_element_located(定位器)定义如下:
class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator)
Parameter : locator - used to find the element returns the WebElement once it is located and visible
Description : An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.
element_to_be_clickable
element_to_be_clickable(定位器)定义如下:
class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator)
Parameter : locator - used to find the element returns the WebElement once it is visible, enabled and interactable (i.e. clickable).
Description : An Expectation for checking an element is visible, enabled and interactable such that you can click it.
评论
0赞
Rao Sahab
4/11/2018
您能否解释一下为什么它有效但其他功能无效。
1赞
wisbucky
11/15/2021
element_to_be_clickable()
肯定有帮助,但在那之后我仍然遇到失败的情况。添加一个 between 和 似乎可以解决问题。.click()
time.sleep(1)
element_to_be_clickable()
.click()
评论
WebDriverWait
的第二个参数不是“延迟”,而是“超时”。