我正在努力写出自己的预期条件.我需要什么...我有一个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
Run Code Online (Sandbox Code Playgroud)
后来在我的代码中:
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" …Run Code Online (Sandbox Code Playgroud) 我希望能够执行类似于 a 的操作WebDriverWait(),即:
WebDriverWait(driver, 60).until(
expected_conditions.text_to_be_present_in_element((By.XPATH, "//tr[5]/td[11]/div"), "1.000000")
)
Run Code Online (Sandbox Code Playgroud)
...对于正则表达式,它在失败之前等待指定的时间。我知道我可以做一些事情,比如……
assert re.search(r"[0,1]{1}.[0-9]{6}", driver.find_element_by_xpath("//tr[5]/td[11]/div").text)
Run Code Online (Sandbox Code Playgroud)
...或者我可以在上面的示例中将搜索替换为匹配。此方法的问题是,如果对象.. (1) 尚未加载或.. (2) 仍在更改为预期内容的过程中,它将失败。我可以做类似的事情...
for x in range (1,60):
try:
assert re.search(r"[0,1]{1}.[0-9]{6}", driver.find_element_by_xpath("//tr[5]/td[11]/div").text)
except AssertionError:
if x < 60:
time.sleep(1)
else:
raise AssertionError
Run Code Online (Sandbox Code Playgroud)
...它每秒检查 60 秒,以查看断言语句的计算结果是否为 true。这可以适合模块或类。我想知道是否有一个更优雅的解决方案,在 Python 中用于 Selenium WebDriver,来处理我不知道的这个问题。