How to use add_init_script method in Playwright Python

Best Python code snippet using playwright-python

operation.py

Source:operation.py Github

copy

Full Screen

...182 async def stop(self):183 self.is_stopped = True184async def login(page: Page, name: str, password: str):185 await page.goto("https://ftty.ydmap.cn/user/login")186 await page.add_init_script(_INIT_SCRIPT)187 driver = Driver(page)188 elem = await driver.wait_and_select(189 '//*[@id="skin-app"]/div/section/form/div[1]/div/div[1]/input'190 )191 await elem.type(name)192 elem = await driver.wait_and_select(193 '//*[@id="skin-app"]/div/section/form/div[2]/div/div/input'194 )195 await elem.type(password)196 await driver.click('//*[@id="skin-app"]/div/section/section/button')197 slider = await driver.wait_and_select('//*[@id="nc_1_n1z"]')198 rect = await slider.bounding_box()199 await page.mouse.move(rect["x"], rect["y"])200 await page.mouse.down()201 await page.mouse.move(rect["x"] + 500, rect["y"])202 await driver.wait_and_select(203 '//*[@id="skin-app"]/section/section/div[3]/div/div/div[1]/img'204 )205_INIT_SCRIPT = """206 Object.defineProperty(navigator, 'webdriver', {207 value: undefined,208 configurable: true209 })210"""211async def new_browser(debug: bool, browser_type: BrowserType):212 browser = await browser_type.launch(213 executable_path="/usr/bin/google-chrome",214 args=[215 "--disable-blink-features",216 "--disable-blink-features=AutomationControlled",217 ],218 headless=not debug,219 )220 ctx = await browser.new_context(no_viewport=True)221 await ctx.add_init_script(_INIT_SCRIPT)222 return ctx.browser223async def new_driver(browser: Browser):224 page = await browser.new_page()225 await page.set_viewport_size({"width": 1920, "height": 1280})226 await page.add_init_script(_INIT_SCRIPT)227 return page228async def select_date(driver: Driver, d: date):229 elems = await driver.wait_and_select_all(230 '//*[@id="skin-app"]/section/div[2]/div[2]/div/ul/li'231 )232 for elem in elems:233 divs = await elem.query_selector_all("div")234 schedulable_date = datetime.strptime(await divs[0].inner_text(), "%Y-%m-%d")235 if datetime.combine(d, datetime.min.time()) == schedulable_date:236 await elem.click()237 return Date(driver, d, await divs[1].inner_text())238 raise KeyError(f"date {d} not found")239def find(iter: Iterable[_T], func: Callable[[_T], bool]) -> _T:240 for item in iter:...

Full Screen

Full Screen

stealth.py

Source:stealth.py Github

copy

Full Screen

...123 yield SCRIPTS['webgl_vendor']124def stealth_sync(page: SyncPage, config: StealthConfig = None):125 """teaches synchronous playwright Page to be stealthy like a ninja!"""126 for script in (config or StealthConfig()).enabled_scripts:127 page.add_init_script(script)128async def stealth_async(page: AsyncPage, config: StealthConfig = None):129 """teaches asynchronous playwright Page to be stealthy like a ninja!"""130 for script in (config or StealthConfig()).enabled_scripts:...

Full Screen

Full Screen

test_add_init_script.py

Source:test_add_init_script.py Github

copy

Full Screen

...12# See the License for the specific language governing permissions and13# limitations under the License.14from playwright.async_api import Error15async def test_add_init_script_evaluate_before_anything_else_on_the_page(page):16 await page.add_init_script("window.injected = 123")17 await page.goto("data:text/html,<script>window.result = window.injected</script>")18 assert await page.evaluate("window.result") == 12319async def test_add_init_script_work_with_a_path(page, assetdir):20 await page.add_init_script(path=assetdir / "injectedfile.js")21 await page.goto("data:text/html,<script>window.result = window.injected</script>")22 assert await page.evaluate("window.result") == 12323async def test_add_init_script_work_with_content(page):24 await page.add_init_script("window.injected = 123")25 await page.goto("data:text/html,<script>window.result = window.injected</script>")26 assert await page.evaluate("window.result") == 12327async def test_add_init_script_throw_without_path_and_content(page):28 error = None29 try:30 await page.add_init_script({"foo": "bar"})31 except Error as e:32 error = e33 assert error.message == "Either path or script parameter must be specified"34async def test_add_init_script_work_with_browser_context_scripts(page, context):35 await context.add_init_script("window.temp = 123")36 page = await context.new_page()37 await page.add_init_script("window.injected = window.temp")38 await page.goto("data:text/html,<script>window.result = window.injected</script>")39 assert await page.evaluate("window.result") == 12340async def test_add_init_script_work_with_browser_context_scripts_with_a_path(41 page, context, assetdir42):43 await context.add_init_script(path=assetdir / "injectedfile.js")44 page = await context.new_page()45 await page.goto("data:text/html,<script>window.result = window.injected</script>")46 assert await page.evaluate("window.result") == 12347async def test_add_init_script_work_with_browser_context_scripts_for_already_created_pages(48 page, context49):50 await context.add_init_script("window.temp = 123")51 await page.add_init_script("window.injected = window.temp")52 await page.goto("data:text/html,<script>window.result = window.injected</script>")53 assert await page.evaluate("window.result") == 12354async def test_add_init_script_support_multiple_scripts(page):55 await page.add_init_script("window.script1 = 1")56 await page.add_init_script("window.script2 = 2")57 await page.goto("data:text/html,<script>window.result = window.injected</script>")58 assert await page.evaluate("window.script1") == 159 assert await page.evaluate("window.script2") == 260async def test_should_work_with_trailing_comments(page):61 await page.add_init_script("// comment")62 await page.add_init_script("window.secret = 42;")63 await page.goto("data:text/html,<html></html>")...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...28 """29 Add an entry to the system crontab.30 """31 raise NotImplementedError32 def add_init_script(self, file):33 """34 Add this file to the init.d directory35 """36 def add_env(self, key, value):37 """38 Add an environemnt variable39 """40 raise NotImplementedError41 def stop(self, service_name):42 """43 Stop a service.44 """45 raise NotImplementedError46 def start(self, service_name):...

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