目标:实现三个页面,两个测试脚本。
练习场景:新建了2个页面对象:百度新闻首页,百度体育新闻首页,具体文件结构如下图,其他和之前项目层级结构保持不变。
1.百度首页页面类代码(baidu_homepage.py),定义了百度新闻的入口
from framework.base_page import BasePage class HomePage(BasePage): input_box = "id=>" search_submit_btn = "xpath=>//*[@id=‘su‘]" # 百度新闻入口 news_link = "xpath=>//*[@id=‘u1‘]/a[@name=‘tj_trnews‘]" def type_search(self,text): self.type(self.input_box,text) def send_submit_btn(self): self.click(self.search_submit_btn) def click_news(self): self.click(self.news_link) self.sleep(2)
2.百度新闻首页的页面类代码(baidu_news_home.py),定义了体育新闻入口
from framework.base_page import BasePage class NewsHomePage(BasePage): # 点击体育新闻入口 sport_link = "xpath=>//*[@id=‘channel-all‘]/div/ul/li[7]/a[@href=‘/sports‘]" def click_sports(self): self.click(self.sport_link) self.sleep(2)
3.百度体育新闻页面类代码(news_sports_home.py)
from framework.base_page import BasePage class SportNewsHomePage(BasePage): # NBA 第一条新闻 nba_link = "xpath=>//*[@id=‘col_nba‘]/div[1]/div[2]/ul[1]/li[1]/a" def click_nba_link(self): self.click(self.nba_link) self.sleep(2)
4.测试类代码(test_nba_news_view.py)
import time import unittest from framework.browser_engine import BrowserEngine from pageobjects.baidu_homepage import HomePage from pageobjects.baidu_news_home import NewsHomePage from pageobjects.news_sport_home import SportNewsHomePage class ViewNBANews(unittest.TestCase): def setUp(self): browse = BrowserEngine(self) self.driver = browse.open_browser(self) def tearDown(self): self.driver.quit() def test_view_nba_views(self): # 初始化百度首页,并点击新闻链接 baiduhome = HomePage(self.driver) baiduhome.click_news() # 初始化一个百度新闻主页对象,点击体育 newshome = NewsHomePage(self.driver) newshome.click_sports() # 初始化一个体育新闻主页,点击NBA sportnewhome = SportNewsHomePage(self.driver) sportnewhome.click_nba_link() sportnewhome.get_window_img() if __name__ == ‘__main__‘: unittest.main()
按照博主的会出现报错:
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
其实,该报错是源于base_page.py里面的,注释掉就能跑下去了。
def click(self,selector): """ 点击元素 :param selector: :return: """ el = self.find_element(selector) try: el.click() #logger.info("The element \‘ %s \‘ was clicked." %el.text) #这一句错了 #错在点击“新闻”后的记录日志,日志中传的参数是“新闻”元素的text属性值。 #我理解此时点击了新闻后页面切换到新闻页面了,所以找不到“新闻”元素了。 except NameError as e: logger.error("Fail to click the element with %s" %e)
参考文章:https://blog.csdn.net/u011541946/article/details/70375555
原文地址:https://www.cnblogs.com/zhaocbbb/p/12672236.html
时间: 2024-10-30 08:11:24