gpt4 book ai didi

Python Selenium 网络驱动程序。写我自己的预期条件

转载 作者:IT老高 更新时间:2023-10-28 21:12:57 26 4
gpt4 key购买 nike

我正在尝试编写我自己的预期条件。我需要什么...我有一个 iframe。我也有一张图片。当图像的 scr 发生变化时,我想继续处理。我做了什么:

class url_changed_condition(object):
'''
Checks whether url in iframe has changed or not
'''
def __init__(self, urls):
self._current_url, self._new_url = urls

def __call__(self, ignored):
return self._current_url != self._new_url

后来在我的代码中:

def process_image(self, locator, current_url):
try:
WebDriverWait(self.driver, 10).until(ec.presence_of_element_located((By.TAG_NAME, u"iframe")))
iframe = self.driver.find_element(*locator)
if iframe:
print "Iframe found!"
self.driver.switch_to_frame(iframe)
WebDriverWait(self.driver, 10).until(ec.presence_of_element_located((By.XPATH, u"//div")))

# WebDriverWait(self.driver, 10).until(
# url_changed_condition(
# (current_url, self.driver.find_element(By.XPATH, u"//a/img").get_attribute(u"src"))))

img_url = self.driver.find_element(By.XPATH, u"//a/img").get_attribute(u"src")
print img_url
self.search_dict[self._search_item].append(img_url)
self.driver.switch_to_default_content()
except NoSuchElementException as NSE:
print "iframe not found! {0}".format(NSE.msg)
except:
print "something went wrong"
import traceback
import sys
type_, value_, trace_ = sys.exc_info()
print type_, value_
print traceback.format_tb(trace_)
finally:
return current_url

此代码有效,但多次返回相同的 url。问题是当我取消注释 url_changed_condition 时,它会在
中出现 TimeoutException(current_url, self.driver.find_element(By.XPATH, u"//a/img").get_attribute(u"src"))
它下面的行工作正常...我不明白。

最佳答案

此主题似乎缺少自定义预期条件的示例

其实很简单。首先,什么是Expected Condition in Python selenium bindings :

有一大套built-in expected condition classes .

让我们通过示例来工作。假设我们想要等到元素的文本以所需文本开头:

from selenium.webdriver.support import expected_conditions as EC

class wait_for_text_to_start_with(object):
def __init__(self, locator, text_):
self.locator = locator
self.text = text_

def __call__(self, driver):
try:
element_text = EC._find_element(driver, self.locator).text
return element_text.startswith(self.text)
except StaleElementReferenceException:
return False

用法:

WebDriverWait(driver, 10).until(wait_for_text_to_start_with((By.ID, 'myid'), "Hello, World!"))

关于Python Selenium 网络驱动程序。写我自己的预期条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19377437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com