Let’s create a simple script that opens a browser, navigates to a page, and takes a screenshot.
1
Create a new Python file
Create a file called first_script.py:
import nodriver as ucasync def main(): # Start the browser browser = await uc.start() # Navigate to a page page = await browser.get('https://www.nowsecure.nl') # Take a screenshot await page.save_screenshot() print("Screenshot saved!") # Clean up browser.stop()if __name__ == '__main__': # Run the async function uc.loop().run_until_complete(main())
2
Run the script
python first_script.py
You should see a browser window open, navigate to the page, and then close. A screenshot will be saved in your current directory.
nodriver uses uc.loop().run_until_complete() instead of asyncio.run() for better compatibility and control.
# Open in the main tabpage = await browser.get('https://www.google.com')# Open in a new tabpage2 = await browser.get('https://www.github.com', new_tab=True)# Open in a new windowpage3 = await browser.get('https://www.stackoverflow.com', new_window=True)
nodriver provides multiple ways to find elements on a page:
# Find by text content (smart matching)button = await page.find("accept all")await button.click()# Find with best match (shortest text wins)login_btn = await page.find("login", best_match=True)# Find all occurrenceslinks = await page.find_all("click here")
All find methods automatically wait for elements to appear (default timeout: 2.5 seconds). This eliminates the need for explicit waits in most cases.
# Wait for body element (indicates page loaded)await tab.select('body')# Or use sleep for a specific durationawait tab.sleep(2)# Wait for events to processawait tab # Short wait for CDP events
Working with iframes
nodriver automatically searches within iframes when using find() and select() methods:
# Searches in main frame and iframeselement = await tab.select("#element-in-iframe")
Handling dynamic content
# Find methods retry until timeout# This element will be found once it appearsbutton = await tab.find("submit", timeout=10)# For elements that might not appearoptional_elem = await tab.find("optional text")if optional_elem: await optional_elem.click()
Taking screenshots
# Save screenshot with default nameawait tab.save_screenshot()# Custom filenameawait tab.save_screenshot("my_screenshot.png")# Get page contenthtml = await tab.get_content()