问题描述
我正在运行django应用,在该范围内,我的页面带有导航栏,当我点击contact
-标签时,该页面会自动向下滚动到我的联系方式。
我正在尝试使用硒测试此行为,但似乎无法弄清楚如何测试页面的实际位置。或者,换句话说,我想验证页面是否实际向下滚动到联系人部分。
现在我正在这样做:
def test_verify_position(
self,browser,live_server
):
""""""
browser.get(live_server.url)
contact_section = browser.find_element_by_id("contact").click()
assert ????
我认为我必须以某种方式获取当前滚动位置坐标。我知道我可以使用.location
获得元素的位置。但是,无论滚动位置如何,元素的相对位置始终是相同的。我尝试过调试:
def test_verify_position(
self,live_server
):
""""""
browser.get(live_server.url)
e = browser.find_element_by_xpath(
"/html/body/section[4]/div/div[1]/h2/strong")
location = e.location
print(location)
browser.find_element_by_css_selector(".nav-contact").click()
e = browser.find_element_by_xpath("/html/body/section[4]/div/div[1]/h2/strong")
location = e.location
print(location)
这将在滚动之前和之后打印相同的坐标。
我还搜索了官方文档https://www.selenium.dev/documentation/en/webdriver/web_element/,但找不到更好的解决方案或与此相关的任何解决方案。
有人知道该怎么做吗?非常感谢您的帮助。预先感谢!
解决方法
编辑:单击“联系人导航”并等待其可见后,您可以在屏幕加载中识别元素之一。
try:
WebDriverWait(driver.visibility_of_element_located,60).until(EC.presence_of_element_located((By.XPATH,'<xpath>')))
except TimeoutException:
assert False
需要导入:
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
,
您要单击它并检查它是否移到那里吗?因为您可以返回当前滚动高度以与元素位置匹配。如果愿意,也可以得到x,y偏移量。
height = driver.execute_script("return document.body.scrollHeight")
print(height)
nav = browser.find_element_by_css_selector(".nav-contact")
location = nav.location
print(location)
browser.execute_script("arguments[0].scrollIntoView();",nav)
nav.click()
Assert.assertTrue(height.equals(location['y']));
#what the answer was
browser.execute_script("return window.pageYOffset")