seldomqa / poium Goto Github PK
View Code? Open in Web Editor NEWPage Objects design pattern test library, support selenium、appium、playwright, etc
Home Page: https://pypi.org/project/poium
License: Apache License 2.0
Page Objects design pattern test library, support selenium、appium、playwright, etc
Home Page: https://pypi.org/project/poium
License: Apache License 2.0
`
# selenium
if by == "id_":
self.__find_element((By.ID, value))
elem = Browser.driver.find_elements(By.ID, value)[self.index]
elif by == "name":
self.__find_element((By.NAME, value))
elem = Browser.driver.find_elements(By.NAME, value)[self.index]
elif by == "class_name":
self.__find_element((By.CLASS_NAME, value))
elem = Browser.driver.find_elements(By.CLASS_NAME, value)[self.index]
elif by == "tag":
self.__find_element((By.TAG_NAME, value))
elem = Browser.driver.find_elements(By.TAG_NAME, value)[self.index]
elif by == "link_text":
self.__find_element((By.LINK_TEXT, value))
elem = Browser.driver.find_elements(By.LINK_TEXT, value)[self.index]
elif by == "partial_link_text":
self.__find_element((By.PARTIAL_LINK_TEXT, value))
elem = Browser.driver.find_elements(By.PARTIAL_LINK_TEXT, value)[self.index]
elif by == "xpath":
self.__find_element((By.XPATH, value))
elem = Browser.driver.find_elements(By.XPATH, value)[self.index]
elif by == "css":
self.__find_element((By.CSS_SELECTOR, value))
elem = Browser.driver.find_elements(By.CSS_SELECTOR, value)[self.index]
`
__get_element 方法如果find_elements是[], 会发生index out of range
你原来的代码:
if self.k == "css":
script = 'document.querySelector("{css}").style.border="2px solid red"'.format(css=self.v)
context.execute_script(script)
使用这种方式,只要定位到了元素就可以修改它的CSS增加边框
ele = driver.find_element_by_class_name("r_item")
driver.execute_script("arguments[0].style.border=\"2px solid red\"", ele)
AttributeError: 'WebElement' object has no attribute 'getText'
使用如下代码:
question = Element(xpath='//*[@id="app"]/main/div/div/div[11]/div/div[4]/div[1]/div[2]/div/div/div')
print(question.get_attribute("xpath"))
给出的attribute为None,查看page_objects.py
中297行的get_attribute(self, name)
函数,未发现问题所在。
麻烦作者大大查看一下,感谢不尽!
虫师大大,我照着你的例子用这个库,在运行时,老是提示“2019-09-02 18:04:35,879 - INFO - timeout 1 times, element not found!”,每一步之间,需要加个等待时间,才能找到对应元素。
在实际项目中,一个测试项目有很多测试页面, 元素定位类是每个页面写一个页面元素类继承一个Page,还是一个网站所有元素都在这个继承Page的页面元素类中? 在调用元素的时候感觉页面元素不是很好区分...比如a页面有个登录,b页面有个登录按钮这种,两个都是登录元素命名一样的实际代表不同页面的元素。 如果是每个页面都继承Page,在使用的时候每个页面都需要实例化一个页面类传入driver? 有最佳实践的demo可参考吗?
想问一下,这个源码中没有找get是什么原因呢?
def setUp(self) -> None:
> LP.open(WebConfig.url)
test_1_Login.py:12:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <PageObjects.LoginPage.LoginPage object at 0x0000023DB1D6C3D0>
uri = 'https://send2boox.com'
def open(self, uri):
"""
:param uri: URI to GET, based off of the root_uri attribute.
"""
root_uri = self.root_uri or ''
> self.driver.get(root_uri + uri)
E AttributeError: 'function' object has no attribute 'get'
C:\Users\keeponzhang\AppData\Local\Programs\Python\Python38\lib\site-packages\poium\selenium.py:79: AttributeError
如题。
class BaiduPage(Page):
input = Element(id_="kw", describe="搜索输入框")
button = Element(id_="su", describe="搜索按钮")
results = Elements(xpath="//div/h3/a", describe="搜索结果")
class TestBaidu02():
def test_01(self):
driver = webdriver.Chrome('/Users/heying/Projects/UI-test-demo/chromeDriver/chromedriver')
page = BaiduPage(driver)
page.get("https://www.baidu.com")
page.input.send_keys("baidu")
page.button.click()
sleep(2)
elem = page.results
for e in elem:
print(e.text)
driver.close()
if name == "main":
pytest.main()
执行结果里面,没有results元素定位时的log.info
======================== 1 passed, 2 warnings in 7.30s =========================
Process finished with exit code 0
PASSED [100%]百度一下,你就知道
官方
百度集团-SW[09888]港股实时行情 - 百度股市通
济南交警联合百度地图发起“2022高考护航计划”
百度-最新招聘信息10条 -百度百聘
度小满钱包
百度短网址
百度官方吧 - 百度贴吧
百度客服电话
百度 - 品牌项目信息
2022-06-07 10:53:53 logging.py | INFO | 🔍 Find element: id=kw. 搜索输入框
2022-06-07 10:53:54 logging.py | INFO | ✅ send_keys('baidu').
2022-06-07 10:53:55 logging.py | INFO | 🔍 Find element: id=su. 搜索按钮
2022-06-07 10:53:56 logging.py | INFO | ✅ click().
按照给到的demo文档来看,应该有个INFO | find 10 elements: xxx
获取方法:
document.querySelectorAll("#kw")[0].value;
Element类的init方法里self.k, self.v = selection_checker(selector),self.k = LOCATOR_LIST.get(by, None) 返回的k类型为什么不做成统一的
能不能把日志输出到文件啊
`class PageWait(object):
def __init__(self, elm, timeout=3):
"""
wait webelement display
"""
try:
timeout_int = int(timeout)
except TypeError:
raise ValueError("Type 'timeout' error, must be type int() ")
for i in range(timeout_int):
if elm is not None:
if elm.is_displayed() is True:
break
else:
sleep(1)
else:
sleep(1)
else:
raise TimeoutError("Timeout, element invisible")`
elm进Pagewait判断的时候如果是个空置,休眠后应该再重新去获取对象
from poium import Page, CSSElement
from time import sleep
from selenium import webdriver
class baiduPage(Page):
a = CSSElement("#s-top-left > a adfasd")
dr = webdriver.Chrome()
page = baiduPage(dr)
page.get("https://www.baidu.com")
page.a.click()
错误信息:
selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'style' of undefined
错误是元素定位,优化poium ,增加元素判断。
node_combiner_loc = Element(xpath='xxxx')
connect_point_list_loc = Elements(xpath='xxxxxx')
def drag_el1_to_el2(self):
self.node_start_loc.click()
print(self.connect_point_list_loc) # 元素list
print(self.node_combiner_loc) # 单个元素
ActionChains(self.driver).drag_and_drop(self.connect_point_list_loc[0], self.node_combiner_loc).perform()
执行时提示:
AttributeError: move_to requires a WebElement
打印出来的元素类型:
connect_point_list_loc:
[<selenium.webdriver.remote.webelement.WebElement (session="1cea47d0fadcbda3a11877b5c3d228bd", element="4f22683b-e2ee-4f42-9f7b-235e4b013598")>]
node_combiner
<poium.page_objects.Element object at 0x7ff003f36a10>
想问下,这种情况要怎么解决?
如题。
举例来说,如果需要判断某个元素的颜色,必须调用value_of_css_property方法并赋值'color'才可以。
有点击有右击,没找到双击操作,求教大佬
page:
from poium import Page, PageElement
class WebviewHomePage(Page):
def get_middle_elements(self):
elements = []
lists = [“首页”,“热门”,“女装”]
for i in lists:
elements.append(PageElement(xpath=f'//div[contains(@id, "quick-entrance-3")]/descendant::div[text()="{i}"]'))
return elements
test:
class TestMallHomepage():
def test_middle_items(self, driver, logger):
webviewhomepage = WebviewHomePage(driver)
mid_elements = webviewhomepage.get_middle_elements()
for element in mid_elements:
element.click()
跑的时候提示:
element.click()
E AttributeError: 'PageElement' object has no attribute 'click'
test_homepage.py:64: AttributeError
`from poium import Page, PageElement
from selenium import webdriver
class BaiduIndexPage(Page):
search_input = PageElement(css="#kw", describe="搜索框")
search_button = PageElement(css="#su", describe="搜索按钮")
class CPCLoginPage(Page):
login = PageElement(id_='id', describe='登录')
pass
class ToutolPage(BaiduIndexPage, CPCLoginPage):
pass
class WebAction(object):
page = ToutolPage(webdriver.Chrome())
# 动态传入类属性
@classmethod
def with_click(cls, click_element):
if hasattr(cls.page, click_element):
getattr(cls.page, click_element).click()
return cls
@classmethod
def with_input(cls):
cls.page.search_input.send_keys('poium')
return cls
@classmethod
def with_open(cls):
cls.page.get('https://www.baidu.com')
return cls
if name == 'main':
weba = WebAction()
weba.with_open().with_input().with_click('search_button')`
感觉DrissionPage的执行效率也很快,相比playwright有一拼。所以也想像Locator、Element、它们一样,对DrissionPage也进行元素剥离,这可以进行兼容改造么?
import os,pytest,sys,random,string
from os.path import abspath, dirname
from time import sleep
base_path = dirname(dirname(abspath(file)))
sys.path.insert(0, base_path)
from config import RunConfig
from util.read_data import ReadData
from common.common_module import CommonKey
from page.element_page import ElementPage
from poium import PageWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
def test_add_object_succ(browser,base_url):
'''
删除对象
'''
dr=CommonKey().Plan_creat_Information_system_check(browser,base_url) #登录返回dr
dr.add_object_button.click()
dr.object_type.click()
dr.object_server.click()
dr.object_IP.send_keys('192.168.30.80')
dr.database_or_system.click()
dr.system_win.click()
sleep(0.5)
dr.button_save.click()
sleep(0.5)
dr.button_quit.click()
right_win=dr.right_windows
ActionChains(dr).move_to_element(right_win).context_click()
dr.del_object.click()
dr.determine_button2.click()
PageWait(dr.Tips)
sleep(0.5)
assert dr.Tips.text=='操作成功!'
想通过以上代码实现右键点击,导入了 ActionChains,在执行过程中出现下面报错
网上对于这方面资料不多,没找到这方面的资料,自己代码功底也不够深
期待您的解答,非常感谢
这是不用poium获取方式
driver.find_elements_by_android_uiautomator('new UiSelector().className("android.widget.Button")‘)[2].click()
使用poium如果这样写
login = PageElement(android_uiautomator='new UiSelector().className("android.widget.Button")‘)
只能获取到第一个,如果我先传入index获取第二个,需要怎么传参呢
selenium.common.exceptions.WebDriverException: Message: Method is not implemented
请问appium是否实现使用CSSElement定位
乱码: [32mINFO ✅ Find element: id=kw �[0m
正常: INFO ✅ Find element: id=kw
简单粗暴在每个打印日志的方法后面加
removeHandler()
如:
def debug(msg):
_logger.debug("DEBUG " + str(msg))
_logger.removeHandler(_handler)
mac本机连接grid,全选快捷键应按grid机器来设置
申明一个元素
class xxPage(Page):
xxbtn = Element(xpath="~~~~~")
在测试类中:
class TestXX:
def test_xxpage(browser):
page = xxPage(broeser)
page.execut_script("arguments[0].click()", page.xxbtn)
在selenium 中都可以通过 driver.execut_script("arguments[0].click()", xxbtn) 执行,但是poium 报错TypeError:Object of type Element is not json serializable,是什么问题呢?
def wait(self, context):
try:
return context.find_element(*self.locator)
except NoSuchElementException:
return None
def find(self, context):
for i in range(self.time_out):
if self.wait(context) is not None:
return self.wait(context)
else:
sleep(1)
else:
return None
提示:
tt = page.wtoip_shangpin.get_attribute('textContent')
E AttributeError: 'NoneType' object has no attribute 'get_attribute'
pageelement、pagewait都被NewPageElement代替了,但是没看到NewPageElement的API文档
源码中第445行:
def is_enabled(self):
"""Returns whether the element is enabled."""
elem = self.__get_element(self.k, self.v)
return elem.is_selected()
返回错误,返回写成 return elem.is_selected() 应该是 return elem.is_enabled()
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.