Overview
The Tab class represents a browser tab (or target) and provides methods for navigation, element interaction, and page manipulation. A tab could be a browser window, an iframe, a service worker, or a background script.
Tab objects are created by the Browser. Access them via browser.tabs, browser.main_tab, or by calling browser.get().
Properties
Reference to the parent Browser instance.
Current URL of the tab (updated when you await tab).
Unique identifier for this target.
Type of target: “page”, “iframe”, “worker”, etc.
Frame identifier for the current page.
URL to open Chrome DevTools inspector for this tab.
Element Finding Methods
find()
Find a single element by text content. Retries until timeout if not found.
async def find(
self,
text: str,
best_match: bool = True,
return_enclosing_element: bool = True,
timeout: Union[int, float] = 10,
) -> Element
Text to search for. Script contents are also considered text.
When True, returns the element with the most similar text length. This helps find specific elements like a “login” button instead of scripts containing “login”. When False, returns the first match (faster).
When True, returns the parent element containing the text node. Set to False to get the text node itself.
Maximum seconds to wait for the element to appear.
Example:
# Find login button
login_btn = await tab.find('Login')
await login_btn.click()
# Find with exact first match (faster)
heading = await tab.find('Welcome', best_match=False)
select()
Find a single element by CSS selector. Retries until timeout if not found.
async def select(
self,
selector: str,
timeout: Union[int, float] = 10,
) -> Element
CSS selector string (e.g., a[href], button[class*=close], a > img[src]).
Maximum seconds to wait for the element to appear.
Example:
# Find submit button
submit = await tab.select('button[type="submit"]')
await submit.click()
# Find link with specific class
link = await tab.select('a.external-link')
print(link.attrs.href)
find_all()
Find multiple elements by text content.
async def find_all(
self,
text: str,
timeout: Union[int, float] = 10,
) -> List[Element]
Example:
# Find all "Read more" links
links = await tab.find_all('Read more')
for link in links:
await link.click()
await tab.wait(1)
select_all()
Find multiple elements by CSS selector.
async def select_all(
self,
selector: str,
timeout: Union[int, float] = 10,
include_frames: bool = False
) -> List[Element]
Whether to include results from iframes.
Example:
# Get all images
images = await tab.select_all('img')
for img in images:
print(img.attrs.src)
# Get all inputs including those in iframes
inputs = await tab.select_all('input', include_frames=True)
xpath()
Find elements by XPath expression.
async def xpath(
self,
xpath: str,
timeout: float = 2.5
) -> List[Element]
Example:
# Find all inline scripts (without src attribute)
scripts = await tab.xpath('//script[not(@src)]')
# Case-insensitive text search
elems = await tab.xpath(
'//text()[contains(translate(., "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"), "test")]'
)
query_selector()
Low-level CSS selector query (equivalent to document.querySelector).
async def query_selector(
self,
selector: str
) -> Element
query_selector_all()
Low-level CSS selector query for multiple elements (equivalent to document.querySelectorAll).
async def query_selector_all(
self,
selector: str
) -> List[Element]
Navigation Methods
get()
Navigate to a URL.
async def get(
self,
url: str = "chrome://welcome",
new_tab: bool = False,
new_window: bool = False
) -> Tab
url
str
default:"chrome://welcome"
URL to navigate to.
Example:
# Navigate in current tab
await tab.get('https://example.com')
# Open in new tab
new_tab = await tab.get('https://example.org', new_tab=True)
back()
Navigate back in history.
forward()
Navigate forward in history.
reload()
Reload the current page.
async def reload(
self,
ignore_cache: bool = True,
script_to_evaluate_on_load: str = None
)
Whether to bypass the cache.
script_to_evaluate_on_load
JavaScript to execute when the page loads.
Example:
# Navigate through history
await tab.get('https://example.com')
await tab.get('https://example.org')
await tab.back() # Back to example.com
await tab.forward() # Forward to example.org
await tab.reload() # Refresh page
Page Content Methods
get_content()
Get the HTML content of the page.
async def get_content(self) -> str
Example:
html = await tab.get_content()
print(html)
evaluate()
Execute JavaScript and get the result.
async def evaluate(
self,
expression: str,
await_promise: bool = False,
return_by_value: bool = True,
max_depth: int = 2
)
JavaScript expression to evaluate.
Whether to await the result if it’s a Promise.
Return the value directly instead of a remote object reference.
Example:
# Get page title
title = await tab.evaluate('document.title')
# Get multiple values
data = await tab.evaluate('''
({
title: document.title,
url: window.location.href,
cookies: document.cookie
})
''')
print(data)
js_dumps()
Dump a JavaScript object with its properties and values as a Python dictionary.
async def js_dumps(
self,
obj_name: str,
return_by_value: bool = True
) -> Union[Dict, Tuple]
Name of the JavaScript object to dump (e.g., “window”, “document”, “navigator”).
Return the value directly as a dict. If False, returns the remote object reference.
Complex objects might not be fully serializable. This method provides a best-effort conversion to Python dictionaries.
Example:
# Dump the navigator object
navigator_data = await tab.js_dumps('navigator')
print(navigator_data['userAgent'])
print(navigator_data['platform'])
# Dump window.performance
performance = await tab.js_dumps('window.performance')
Window Management
maximize()
Maximize the window.
minimize()
Minimize the window.
fullscreen()
Set window to fullscreen.
async def fullscreen(self)
medimize()
Restore window to normal size (not minimized, maximized, or fullscreen).
This is a convenience alias for set_window_state(state="normal").
set_window_size()
Set window position and size.
async def set_window_size(
self,
left: int = 0,
top: int = 0,
width: int = 1280,
height: int = 1024
)
Example:
# Set custom window size
await tab.set_window_size(0, 0, 1920, 1080)
# Maximize window
await tab.maximize()
activate()
Bring this tab to the front.
close()
Close this tab.
Scroll down by a specified amount.
async def scroll_down(self, amount: int = 25)
Scroll up by a specified amount.
async def scroll_up(self, amount: int = 25)
Example:
# Scroll down 100 pixels
await tab.scroll_down(100)
# Scroll up 50 pixels
await tab.scroll_up(50)
Mouse Interaction
mouse_move()
Move the mouse to specific coordinates.
async def mouse_move(
self,
x: float,
y: float,
steps: int = 10,
flash: bool = False
)
Number of steps for smooth movement.
Flash the point for visibility.
mouse_click()
Click at specific coordinates.
async def mouse_click(
self,
x: float = None,
y: float = None,
button: str = 'left',
buttons: int = 1,
modifiers: int = 0,
click_count: int = 1
)
mouse_drag()
Drag from one position to another.
async def mouse_drag(
self,
from_x: float,
from_y: float,
to_x: float,
to_y: float,
steps: int = 20
)
Screenshots
save_screenshot()
Save a screenshot of the page.
async def save_screenshot(
self,
filename: str = 'screenshot.png',
format: str = 'png',
full_page: bool = False
)
filename
str
default:"screenshot.png"
Path to save the screenshot.
Image format: ‘png’ or ‘jpeg’.
Capture the entire page, not just the viewport.
Example:
# Save viewport screenshot
await tab.save_screenshot('page.png')
# Save full page screenshot
await tab.save_screenshot('fullpage.png', full_page=True)
# Save as JPEG
await tab.save_screenshot('page.jpg', format='jpeg')
File Downloads
download_file()
Download a file from a URL.
async def download_file(
self,
url: str,
filename: Optional[PathLike] = None
) -> pathlib.Path
URL of the file to download.
Optional filename. If None, uses the filename from the URL.
Example:
# Download file
path = await tab.download_file(
'https://example.com/file.pdf',
'downloaded.pdf'
)
print(f"Downloaded to: {path}")
set_download_path()
Set the default download directory.
async def set_download_path(self, path: Union[str, PathLike])
Storage Methods
get_local_storage()
Get all localStorage items.
async def get_local_storage(self) -> dict
set_local_storage()
Set localStorage items.
async def set_local_storage(self, items: dict)
Example:
# Set localStorage
await tab.set_local_storage({
'theme': 'dark',
'user': 'john'
})
# Get localStorage
storage = await tab.get_local_storage()
print(storage)
Anti-Detection & Security
verify_cf()
Verify Cloudflare checkbox challenge automatically. This method locates and clicks the Cloudflare verification checkbox.
async def verify_cf(
self,
template_image: str = None,
flash: bool = False
)
Custom template image for locating the checkbox. The default template is in English. If you need a different language, create a cropped image (111x71 pixels) with the checkbox target centered.
If True, flashes the located checkbox area for debugging.
This method only works when NOT in expert mode. Requires the opencv-python package to be installed.
Example:
# Verify Cloudflare challenge
await tab.verify_cf()
# Use custom template for different language
await tab.verify_cf(template_image='path/to/custom_cf_template.png')
bypass_insecure_connection_warning()
Bypass the browser’s insecure connection warning (e.g., when a certificate is invalid).
async def bypass_insecure_connection_warning(self)
This method sends the special string “thisisunsafe” to bypass Chrome’s SSL warning page.
Example:
# Navigate to site with invalid certificate
await tab.get('https://site-with-invalid-cert.com')
# Bypass the warning
await tab.bypass_insecure_connection_warning()
Waiting and Timing
wait()
Wait for a specified time.
async def wait(self, t: Union[int, float] = 0.5)
sleep()
Alias for wait().
async def sleep(self, t: float | int = 1)
wait_for()
Wait for a condition to be true.
async def wait_for(
self,
condition: Callable,
timeout: float = 10
)
Example:
# Wait 2 seconds
await tab.wait(2)
# Wait for element to appear
await tab.wait_for(lambda: tab.select('button#submit', timeout=0.1))
Inspector
open_external_inspector()
Open Chrome DevTools inspector in your system browser.
async def open_external_inspector(self)
Example:
# Open inspector for debugging
await tab.open_external_inspector()
Custom CDP Commands
Send custom Chrome DevTools Protocol commands:
from nodriver import cdp
# Navigate using CDP
await tab.send(cdp.page.navigate(url='https://example.com'))
# Take screenshot using CDP
screenshot = await tab.send(cdp.page.capture_screenshot())
Examples
Complete scraping example
import nodriver as uc
async def main():
browser = await uc.start()
tab = await browser.get('https://example.com')
# Find and click button
button = await tab.find('Click me')
await button.click()
# Wait for content to load
await tab.wait(2)
# Get all links
links = await tab.select_all('a')
for link in links:
print(f"Link: {link.attrs.href}")
# Take screenshot
await tab.save_screenshot('result.png')
browser.stop()
uc.loop().run_until_complete(main())
See also