How to use wait_for_element_state method in Playwright Python

Best Python code snippet using playwright-python

Getir.py

Source:Getir.py Github

copy

Full Screen

...135 # home screen136 self.page.click(f'img[alt="{category.name}"]')137 sleep(2) # WAİT FOR PAGE LOAD WİTH PLAYWRIGHT NOT TIME.SLEEP138 self.page.query_selector(139 "div[name='category-products']").wait_for_element_state("visible")140 all_query = self.page.query_selector_all(141 "div[data-testid='breadcrumb-item']")142 for query in all_query:143 if (query.inner_text() == category.name):144 break145 # dongu = True146 # while dongu:147 # all_query = self.page.query_selector_all("div[data-testid='breadcrumb-item']")148 # for query in all_query:149 # if (query.inner_text() == category.name):150 # dongu = False151 elif ("https://getir.com/kategori/" in self.page.url):152 # category page153 collapse_div = self.page.query_selector(154 'div[data-testid="collapse"]')155 panel_divs = collapse_div.query_selector_all(156 'div[data-testid="panel"]')157 for panel_div in panel_divs:158 span_text = panel_div.query_selector(159 'span[data-testid="text"]').inner_text()160 if span_text == category.name:161 panel_div.click()162 else:163 # not in category page164 self.page.goto(gv.GETIR_HOME)165 self.go_category(category)166 def go_sub_category(self, sub_category: SubCategory):167 category = self.database.get_category_with_sub_category(sub_category)168 if category != None:169 self.go_category(category)170 collapse_div = self.page.query_selector(171 'div[data-testid="collapse"]')172 panel_divs = collapse_div.query_selector_all(173 'div[data-testid="panel"]')174 for panel_div in panel_divs:175 span_text = panel_div.query_selector(176 'span[data-testid="text"]').inner_text()177 if span_text == category.name:178 panel_body = panel_div.query_selector(179 'div[data-testid="panel-body"]')180 if panel_body != None:181 a_list = panel_body.query_selector_all('a')182 for a in a_list:183 span_text = a.query_selector(184 'span[data-testid="text"]').inner_text()185 if span_text == sub_category.name:186 a.click()187 break188 def clear_text_for_sql_injection(self, text: str) -> str:189 return text.replace("'", "").replace('"', "").replace("\\", "").replace("'", "").replace("é", "")190 def clear_price(self, price: str) -> float:191 return float(price.replace("₺", "").replace(",", "."))192 def get_all_getir_products(self, pass_yeni_urunler : bool = True, pass_indirimler : bool = True, pass_ilginizi_cekebilecekler : bool = True ):193 for category in self.category_list:194 self.page.goto(gv.GOOGLE)195 if pass_yeni_urunler and category.name == "Yeni Ürünler":196 print("Pass Yeni Ürünler")197 pass198 elif pass_indirimler and category.name == "İndirimler":199 print("Pass İndirimler")200 pass201 else:202 for sub_category in self.get_sub_categories_with_category(category):203 if pass_ilginizi_cekebilecekler and sub_category.name == "İlginizi Çekebilecekler":204 print("Pass İlginizi Çekebilecekler")205 pass206 else:207 self.go_sub_category(sub_category)208 self.get_product_list_web(sub_category)209 def get_card_wrapper(self, sub_category: SubCategory):210 self.page.query_selector(211 "div[name='category-products']").wait_for_element_state("visible")212 213 div_category_products = self.page.query_selector(214 "div[name='category-products']")215 216 div_list = div_category_products.query_selector_all("div")217 for div in div_list:218 header_div = div.query_selector(219 "div[class^='style__HeaderWrapper']")220 if header_div != None:221 h5_text = header_div.query_selector("h5").inner_text()222 if h5_text == sub_category.name:223 card_wrapper = div.query_selector(224 "div[class^='style__CardWrapper']")225 html = card_wrapper.inner_html()...

Full Screen

Full Screen

auto.py

Source:auto.py Github

copy

Full Screen

...82 score = await score_ele.inner_text()83 print(f'分数 {score}')84 qr_code = page.locator('body > uni-app > uni-page > uni-page-wrapper > uni-page-body > uni-view > uni-view.uni-popup.center > uni-view:nth-child(2) > uni-view > uni-view > uni-view:nth-child(2) > uni-image > img')85 hd = await qr_code.element_handle()86 await hd.wait_for_element_state('stable')87 await page.screenshot(path='result.png', type='png')88 return score89async def submit_paper(page):90 locator = page.locator('body > uni-app > uni-page > uni-page-wrapper > uni-page-body > uni-view > uni-view.paper-foot > uni-button')91 await locator.click(delay=random.randrange(100, 300))92async def start_paper(page):93 await page.wait_for_selector('.paper-title.exam-qustion-content')94 content = await page.content()95 questions = do_extract_questions(content)96 db = load_db(OPT.db)97 for q in questions:98 print(f'正在答题 {q.no}')99 an = find_answer(db, q)100 if q.type == '单选题':...

Full Screen

Full Screen

position.py

Source:position.py Github

copy

Full Screen

1from playwright.sync_api import Playwright, sync_playwright2import time3#['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_dispatcher_fiber', '_gather', '_impl_obj', '_loop', '_sync', '_wrap_handler', 'as_element', 'bounding_box', 'check', 'click', 'content_frame', 'dblclick', 'dispatch_event', 'dispose', 'eval_on_selector', 'eval_on_selector_all', 'evaluate', 'evaluate_handle', 'fill', 'focus', 'get_attribute', 'get_properties', 'get_property', 'hover', 'inner_html', 'inner_text', 'input_value', 'is_checked', 'is_disabled', 'is_editable', 'is_enabled', 'is_hidden', 'is_visible', 'json_value', 'on', 'once', 'owner_frame', 'press', 'query_selector', 'query_selector_all', 'remove_listener', 'screenshot', 'scroll_into_view_if_needed', 'select_option', 'select_text', 'set_input_files', 'tap', 'text_content', 'type', 'uncheck', 'wait_for_element_state', 'wait_for_selector']4class Playwright_api:5 '''Playwright目前支持的定位引擎有:css、xpath、text:'''6 def __init__(self,page):7 self.page=page8 def open_url(self,url):9 '''打开浏览器'''10 #self.page.goto("https://www.baidu.com/")11 self.page.goto(url)12 time.sleep(3)13 return self.page14 def single_selector(self,j_str):15 '''选择单个元素'''16 print(str(j_str),'选择一个',self.page)17 obj=self.page.query_selector(j_str)18 return obj19 def all_selector(self,j_str):20 '''选择多个元素'''21 obj=self.page.query_selectorAll(j_str)22 return obj23 def wait_selector(self,j_str):24 '''选择单个元素,并且自动等待到元素可见、可操作'''25 obj=self.page.waitFor_selector(j_str)26 return obj27 def dialogue(self,js):28 '''js会话'''29 print('进了js会话')30 self.page.evaluate(js)31 def Drag(self,start_width,start_height,Finish_width,Finish_height):32 '''拖拽'''33 print('进了拖拽没')34 self.page.mouse.move(start_width, start_height)#起始点35 self.page.mouse.down()#按下36 self.page.mouse.move(Finish_width, Finish_height)#终点37 self.page.mouse.up()#松开38 #return self.page39# 选择单个元素:querySelector(engine=body)40# 选择多个元素:querySelectorAll(engine=body)41# 选择单个元素,并且自动等待:waitForSelector(engine=body)42#page.keyboard.press43#dblclick右键44#touchscreen.tap(x, y)45#点击46#输入47#键盘事件48class action:49 def __init__(self,page,path_name,obj=None):50 self.page=page51 self.obj=obj52 self.path_name=path_name53 def Left_click(self):54 '''左键单击'''55 print(self.page,'一坑更比一坑坑')56 self.page.click()57 def Double_click(self):58 '''左键双击'''59 print(self.page,'一坑更比一坑坑')60 self.page.dblclick()61 def Right_click(self):62 '''右键键单击'''63 self.page.mouse.move(200, 405)#起始点64 self.page.mouse.down()#按下65 self.page.mouse.move(400, 605)#终点66 self.page.mouse.up()#松开67 def Press(self,width,height,t):68 '''长按'''69 self.page.mouse.move(width, height)#按压位置70 self.page.mouse.down()#按下71 time.sleep(t)#按压时间72 self.page.mouse.up()#松开73 def enter(self,value):74 '''输入'''75 print(self.page,value,'下班之后轻松秒杀')76 self.page.fill(value)77 #return 78 def text_val(self):79 '''获取元素文本'''80 val=self.page.text_content()81 print(self.path_name,'到哪儿了兄弟',val)82 self.obj({self.path_name:val})#通过回调函数返回83 def xpath_val(self):84 '''获取元素坐标'''85 val=self.page.bounding_box()86 print(self.path_name,'\n\n获取元素坐标\n\n',val)87 self.obj({self.path_name:val})#通过回调函数返回88 89 90 def Upload_file(self,selector,file_url):91 '''上传文件'''92 #self.page.setInputFiles('input#upload', 'myfile.pdf')93 self.page.setInputFiles(selector,file_url)94 def deal_with(self,res):95 """参数处理"""96 #{'csrfmiddlewaretoken': 'sjAuyfpHGhnjdLqi9ZNBhFx48bUfq89FTqH6BwZWOesQm6XJxO1JIqxFKW4daEPL', 'path_name': '进入到dpa登录', 'sleep_time': '1', 'Positioning': '12', 'url': 'http://192.168.3.185/dpa/login'}97 #{'path_name': '输入密码', 'sleep_time': '1', 'Positioning': '0', 'title': '[placeholder=\\"请输入密码\\"]', 'interest': '2', 'data': '123456'} 关键中的关键98 #{'path_name': '点击登录', 'sleep_time': '1', 'Positioning': '0', 'title': 'button:has-text(\\"登录\\")', 'interest': '0'}99 interest = res.get('interest')#获取操作方式100 sleep_time = int(res.get('sleep_time'))#获取睡眠时间,这里前端得效验101 print('走进了我的心房',interest,res) 102 if interest=='0':103 #左键点击104 print('左键点击')105 self.Left_click()106 time.sleep(sleep_time)107 return None108 # elif interest=='1':109 # #清空输入框110 # obj.clear()111 # return None112 elif interest=='2':113 #输入内容114 data = res.get('data')#获取data115 self.enter(data)116 time.sleep(sleep_time)117 return None118 elif interest=='3':119 #获取div内容120 Text=self.text_val()121 time.sleep(sleep_time)122 return Text123 elif interest=='4':124 #右键点击125 self.Right_click()126 time.sleep(sleep_time)127 return None128 elif interest=='5':129 #双击130 print('左键双击')131 self.Double_click()132 time.sleep(sleep_time)133 return None134 elif interest=='6':135 #长按136 self.Press(width,height,t)137 time.sleep(sleep_time)138 return None139 # elif interest=='7':140 # #回退141 # obj.back()142 # return None143 # elif interest=='8':144 # #回车145 # obj.send_keys(Keys.ENTER)146 # return None147 elif interest=='9':148 #获取坐标149 Text=self.xpath_val()150 time.sleep(sleep_time)151 return Text152 ...

Full Screen

Full Screen

web_elements.py

Source:web_elements.py Github

copy

Full Screen

...56 self.set_value(text)57 return self58 def send_keys(self, text, delay=10):59 if self.selector is None:60 self.element.wait_for_element_state(state="visible")61 self.element.type(text, delay=delay)62 else:63 self.page.wait_for_selector(self.selector, state="visible")64 self.page.type(self.selector, text, delay=delay)65 return self66 def click(self):67 if self.selector is None:68 self.element.click()69 else:70 self.page.click(self.selector)71 return self72 def should_be_visible(self):73 if self.selector is None:74 self.element.wait_for_element_state(state="visible")75 else:76 self.page.wait_for_selector(self.selector, state="visible")77 return self78 def should_be_hidden(self):79 if self.selector is None:80 self.element.wait_for_element_state(state="hidden")81 else:82 self.page.wait_for_selector(self.selector, state="hidden")83 return self84 def is_enabled(self):85 # if not self.page.evaluate('''(el) => { return el.disabled }''', arg=self.element_handle):86 # return True87 if self.selector is None:88 return self.element.is_enabled()89 else:90 return self.page.is_enabled(self.selector)91 def is_visible(self):92 if self.selector is None:93 return self.element.is_visible()94 else:95 return self.page.is_visible(self.selector)96 def is_displayed(self):97 if self.selector is None:98 return self.element.is_disabled()99 else:100 return self.page.is_disabled(self.selector)101 def is_checked(self):102 if self.selector is None:103 return self.element.is_checked()104 else:105 return self.page.is_checked(self.selector)106 def value(self):107 if self.selector is None:108 return self.element.evaluate('''(el) => { return el.value }''')109 else:110 return self.page.evaluate('''(el) => { return el.value }''', arg=self.element)111 def press_tab(self):112 self.page.keyboard.press('Tab')113 return self114 def press_enter(self):115 self.page.keyboard.press('Enter')116 return self117 def inner_text(self):118 if self.selector is None:119 self.element.wait_for_element_state(state="visible")120 return self.element.inner_text()121 else:122 self.page.wait_for_selector(self.selector, state="visible")123 return self.page.inner_text(self.selector)124 def scroll_into_view(self, behavior: Literal["auto", "smooth", "instant"] = "auto",125 block: Literal["start", "center", "end", "nearest"] = "center",126 inline: Literal["start", "center", "end", "nearest"] = "nearest"):127 if self.selector is None:128 return self.element.evaluate(expression='''el => { el.scrollIntoView({behavior: \"%s\", block: \"%s\", inline: \"%s\"}); }''' % (behavior, block, inline))129 else:130 self.page.eval_on_selector(self.selector, expression='''(el) => { el.scrollIntoView({behavior: \"%s\", block: \"%s\", inline: \"%s\"}); }''' % (behavior, block, inline))131 return self132 def scroll_into_view_if_needed(self):133 if self.selector is None:...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful