### Full Example: Connecting and Using DrissionPage
Source: https://www.drissionpage.cn/tutorials/TgeBrowser
This comprehensive example demonstrates the entire workflow: creating and starting a browser, retrieving connection details, and connecting using multiple methods, followed by basic operations.
```Python
import requests
import time
from DrissionPage import Chromium, ChromiumPage, ChromiumOptions
API_BASE_URL = "http://127.0.0.1:50326"
API_KEY = "your_api_key"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# 创建并启动浏览器
response = requests.post(
f"{API_BASE_URL}/api/browser/create",
json={"browserName": "连接测试", "proxy": {"protocol": "direct"}},
headers=headers
)
env_id = response.json()["data"]["envId"]
response = requests.post(
f"{API_BASE_URL}/api/browser/start",
json={"envId": env_id},
headers=headers
)
# 获取连接信息
data = response.json()["data"]
port = data["port"]
ws_url = data["ws"]
print(f"调试端口: {port}")
print(f"WebSocket: {ws_url}")
time.sleep(3)
# ========== 方式 1: ChromiumOptions ==========
co = ChromiumOptions().set_local_port(port)
page1 = ChromiumPage(addr_or_opts=co)
print(f"方式1 连接成功: {page1.title}")
# ========== 方式 2: 端口号 ==========
page2 = Chromium(port)
print(f"方式2 连接成功: {page2.title}")
```
--------------------------------
### Start Listener and Get Packets in Steps
Source: https://www.drissionpage.cn/browser_control/listener
Starts listening for network packets containing 'gitee.com/explore', accesses a URL, and then iterates through captured packets, printing each URL and clicking the next page button until five packets are processed.
```Python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.listen.start('gitee.com/explore') # 开始监听,指定获取包含该文本的数据包
tab.get('https://gitee.com/explore/all') # 访问网址
i = 0
for packet in tab.listen.steps():
print(packet.url) # 打印数据包url
tab('@rel=next').click() # 点击下一页
i += 1
if i == 5:
break
```
--------------------------------
### Start Browser and Visit Website
Source: https://www.drissionpage.cn/get_start/before_start
This snippet attempts to launch the latest available Chrome tab and navigate to the DrissionPage website. If successful, no further setup is needed.
```python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.get('http://DrissionPage.cn')
```
--------------------------------
### Example Timeouts Output
Source: https://www.drissionpage.cn/browser_control/browser_options
Example output showing the structure and values of the timeouts configuration.
```json
{
'base': 10,
'page_load': 30,
'script': 30
}
```
--------------------------------
### Full Example: TgeBrowser and DrissionPage Integration
Source: https://www.drissionpage.cn/tutorials/TgeBrowser
This comprehensive example demonstrates the entire process of creating a browser environment in TgeBrowser, launching it, and then connecting to it with DrissionPage to perform automated tasks. Ensure TgeBrowser is running and accessible via the API.
```python
import requests
import time
from DrissionPage import ChromiumPage, ChromiumOptions
# ========== 配置 ==========
API_BASE_URL = "http://127.0.0.1:50326"
API_KEY = "your_api_key_here" # 在 TgeBrowser 客户端获取
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# ========== 步骤 1: 创建浏览器环境 ==========
print("1. 创建浏览器环境...")
response = requests.post(
f"{API_BASE_URL}/api/browser/create",
json={"browserName": "自动化测试", # 环境名称
"proxy": {
"protocol": "socks5",
"host": "proxy.example.com",
"port": 8888,
"username": "username",
"password": "password",
},
"fingerprint": {
"os": "Windows",
"platformVersion": 11,
"kernel": "135",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.9.2537 Safari/537.36",
"canvas": True,
"speechVoices": True,
"clientRects": True,
"fonts": ["Arial", "Courier New"],
"disableTLS": [],
"resolution": "1920x1080",
"ram": 8,
"cpu": 4,
"language": "en-US",
"languageBaseIp": True,
"timezone": "Europe/Amsterdam",
"timezoneBaseIp": True,
"hardwareAcceleration": True,
"disableSandbox": False,
"startupParams": "",
"deviceName": "DESKTOP-ABCD",
"portScanProtection": ""
},
"startInfo": {
"startPage": {
"mode": "custom",
"value": [
"https://www.baidu.com"
]
},
"otherConfig": {
"openConfigPage": False,
"checkPage": True,
"extensionTab": True
}
}
},
headers=headers
)
env_id = response.json()["data"]["envId"]
print(f" 环境创建成功,ID: {env_id}")
# ========== 步骤 2: 启动浏览器 ==========
print("2. 启动浏览器...")
response = requests.post(
f"{API_BASE_URL}/api/browser/start",
json={"envId": env_id},
headers=headers
)
debug_port = response.json()["data"]["port"]
print(f" 浏览器已启动,调试端口: {debug_port}")
# ========== 步骤 3: 连接 DrissionPage ==========
print("3. 连接 DrissionPage...")
time.sleep(3) # 等待浏览器完全启动
# 方式1: 通过端口连接(推荐)
co = ChromiumOptions().set_local_port(debug_port)
page = ChromiumPage(addr_or_opts=co)
# 方式2: 直接使用端口号
# from DrissionPage import Chromium
# page = Chromium(debug_port)
# 方式3: 使用地址:端口
# page = Chromium(f'127.0.0.1:{debug_port}')
# 方式4: 使用 WebSocket URL(需要先获取 ws_url)
# ws_url = response.json()["data"]["ws"]
# page = Chromium(ws_url)
print(" DrissionPage 连接成功")
# ========== 步骤 4: 执行自动化操作 ==========
print("4. 执行自动化操作...")
# 访问网页
page.get('https://www.example.com')
print(f" 当前页面: {page.title}")
# 更多操作示例
page.get_screenshot('screenshot.png') # 截图
print(" 已保存截图")
print("\n完成!")
```
--------------------------------
### Install Dependencies
Source: https://www.drissionpage.cn/tutorials/TgeBrowser
Install the necessary Python packages for DrissionPage and requests.
```bash
pip install DrissionPage requests
```
--------------------------------
### Start Listener and Wait for Packets
Source: https://www.drissionpage.cn/browser_control/listener
Starts listening for network packets containing 'gitee.com/explore' and clicks the next page button five times, waiting for and printing the URL of each captured packet.
```Python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.get('https://gitee.com/explore/all') # 访问网址,这行产生的数据包不监听
tab.listen.start('gitee.com/explore') # 开始监听,指定获取包含该文本的数据包
for _ in range(5):
tab('@rel=next').click() # 点击下一页
res = tab.listen.wait() # 等待并获取一个数据包
print(res.url) # 打印数据包url
```
--------------------------------
### Install DrissionPage
Source: https://www.drissionpage.cn/get_start/installation
Use this command to install the latest stable version of DrissionPage.
```bash
pip install DrissionPage
```
--------------------------------
### Record Browser Video
Source: https://www.drissionpage.cn/browser_control/screen
Records the browser activity as a video. This example sets the save path, selects video recording mode, starts recording, waits for 3 seconds, and then stops the recording. Ensure 'opencv-python' is installed for video recording.
```python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.screencast.set_save_path('video') # 设置视频存放路径
tab.screencast.set_mode.video_mode() # 设置录制
tab.screencast.start() # 开始录制
tab.wait(3)
tab.screencast.stop() # 停止录制
```
--------------------------------
### Take Over Manually Opened Browser on a Specific Port
Source: https://www.drissionpage.cn/browser_control/connect_browser
Manually start a browser on a specific port and then use DrissionPage to take over that instance. This example shows how to connect to a browser that has been manually launched on port 9333.
```Python
from DrissionPage import Chromium
browser = Chromium(9333) # Browser already manually started on port 9333
```
--------------------------------
### Example of Immediate Exception on Element Not Found
Source: https://www.drissionpage.cn/browser_control/get_elements/behavior
An example demonstrating the immediate `ElementNotFoundError` when `Settings.set_raise_when_ele_not_found(True)` is active and an element does not exist.
```Python
from DrissionPage import Chromium
from DrissionPage.common import Settings
Settings.set_raise_when_ele_not_found(True)
tab = Chromium().latest_tab
tab.get('https://www.baidu.com')
ele = tab('#abcd') # ('#abcd')这个元素不存在
```
--------------------------------
### Upgrade to a Specific Version
Source: https://www.drissionpage.cn/get_start/installation
Use this command to install a particular version of DrissionPage, for example, 4.0.0b17.
```bash
pip install DrissionPage==4.0.0b17
```
--------------------------------
### Wait for Page Load Start
Source: https://www.drissionpage.cn/browser_control/waiting
This method is used to wait for a page to enter the loading state. It prevents issues where elements with the same locator on the next page might be accessed too early. Note that get() already includes waiting for the load start.
```python
ele.click() # 点击某个元素
tab.wait.load_start() # 等待页面进入加载状态
# 执行在新页面的操作
print(page.title)
```
--------------------------------
### wait.download_begin()
Source: https://www.drissionpage.cn/browser_control/browser_object
Waits for a browser download to start. This is particularly useful for downloads initiated from temporary or hidden tabs.
```APIDOC
## wait.download_begin()
### Description
Waits for a browser download to start. This is particularly useful for downloads initiated from temporary or hidden tabs.
### Method
```
wait.download_begin(timeout: float | None = None, cancel_it: bool = False)
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **timeout** (float | None) - Optional - The timeout duration in seconds. If `None`, the page object's default timeout is used.
* **cancel_it** (bool) - Optional - If `True`, the download task will be cancelled if the timeout is reached. Defaults to `False`.
### Request Example
```json
{
"example": "wait.download_begin(timeout=30)"
}
```
### Response
#### Success Response (200)
* **DownloadMission** - Returns a download mission object if the download starts successfully.
* **False** - Returns `False` if the wait fails or times out.
#### Response Example
```json
{
"example": "download_mission_object"
}
```
```
--------------------------------
### Chained Actions Example
Source: https://www.drissionpage.cn/browser_control/actions
Demonstrates performing multiple actions in a single chained sequence for efficiency.
```python
tab.actions.move_to(ele).click().type('some text')
```
--------------------------------
### 使用 get() 方法访问 URL
Source: https://www.drissionpage.cn/browser_control/visit
使用 get() 方法跳转到指定的 URL。当连接失败时,程序会进行重试。此方法可用于访问本地文件路径。
```python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.get('http://DrissionPage.cn')
```
--------------------------------
### Get Console Log Message
Source: https://www.drissionpage.cn/browser_control/console
This snippet demonstrates how to start console listening, execute JavaScript to log a message, wait for the message, and print its text content.
```python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.console.start()
tab.run_js('console.log("DrissionPage");')
data = tab.console.wait()
print(data.text) # Output: DrissionPage
```
--------------------------------
### 设置 get() 方法的超时和重试参数
Source: https://www.drissionpage.cn/browser_control/visit
通过 retry、interval 和 timeout 参数来配置 get() 方法的重试次数、重试间隔和加载超时时间。如果未指定 timeout,将使用 ChromiumPage 的 page_load 默认值。
```python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.get('http://DrissionPage.cn', retry=1, interval=1, timeout=1.5)
```
--------------------------------
### Get Specific Element by Index
Source: https://www.drissionpage.cn/browser_control/get_elements/filter
Use `filter_one()` with an index to retrieve a specific element from a list. This example gets the second element with text containing '图'.
```python
ele = eles.filter_one(2).text('图') # 获取第二个文本带有“图”字的元素
```
--------------------------------
### Initialize and Use WebPage with Mode Switching
Source: https://www.drissionpage.cn/browser_control/pages
Shows how to initialize WebPage, navigate to a URL, and switch its operating mode. WebPage is recommended for scenarios requiring mode changes.
```Python
from DrissionPage import WebPage
page = WebPage()
page.get('http://DrissionPage.cn')
print(page.title)
page.change_mode()
print(page.title)
```
--------------------------------
### Batch Get Element Texts
Source: https://www.drissionpage.cn/browser_control/get_ele_info
Demonstrates how to get the text content of multiple elements found by a selector. This example shows fetching all 'a' tags within a specific element.
```python
from DrissionPage import SessionPage
page = SessionPage()
page.get('https://www.baidu.com')
ele = page('#s-top-left')
sub_eles = ele.eles('t:a')
print(sub_eles.get.texts())
```
--------------------------------
### Basic Browser Automation Example
Source: https://www.drissionpage.cn/browser_control/intro
This snippet demonstrates the fundamental workflow: creating a browser instance, navigating to a page, finding elements, inputting text, clicking a button, and extracting information.
```Python
from DrissionPage import Chromium
browser = Chromium()
# 获取标签页对象
tab = browser.latest_tab
# 访问网页
tab.get('https://www.baidu.com')
# 获取文本框元素对象
ele = tab.ele('#kw')
# 向文本框元素对象输入文本
ele.input('DrissionPage')
# 点击按钮,上两行的代码可以缩写成这样
tab('#su').click()
# 获取所有
元素
links = tab.eles('tag:h3')
# 遍历并打印结果
for link in links:
print(link.text)
```
--------------------------------
### Initialize Chromium with specific options and disable session options
Source: https://www.drissionpage.cn/advance/packaging
This example demonstrates initializing Chromium with custom options, including setting a local port, cache path, and user data path using relative directories. It also shows how to disable session options by setting 'session_options=False' and then accessing the latest tab to navigate to a URL.
```python
from DrissionPage import Chromium, ChromiumOptions
co = (ChromiumOptions(read_file=False)
.set_local_port(9888)
.set_cache_path(r'.\Chrome\chrome.exe')
.set_user_data_path(r'.\Chrome\userData'))
browser = Chromium(addr_or_opts=co, session_options=False)
# Note: session_or_options=False
tab = browser.latest_tab
tab.get('http://DrissionPage.cn')
```
--------------------------------
### Import ChromiumOptions
Source: https://www.drissionpage.cn/browser_control/browser_options
Import the ChromiumOptions class from the DrissionPage library to start configuring browser options.
```APIDOC
## Import
### Description
Import the necessary class to manage browser options.
### Code
```python
from DrissionPage import ChromiumOptions
```
```
--------------------------------
### Navigate to URL
Source: https://www.drissionpage.cn/get_start/examples/control_browser
Uses the get() method to navigate to a specified URL and waits for the page to fully load before proceeding.
```Python
tab.get('https://gitee.com/login')
```
--------------------------------
### Get Parent Element by Level
Source: https://www.drissionpage.cn/browser_control/get_elements/relative
Retrieves a specified level of parent element. Starts from level 1 for the immediate parent.
```python
# 获取 ele1 的第二层父元素
ele2 = ele1.parent(2)
```
--------------------------------
### Start Browser Environment
Source: https://www.drissionpage.cn/tutorials/TgeBrowser
Initiate the browser using the obtained envId by calling the /api/browser/start endpoint. This returns a debug port necessary for connecting DrissionPage.
```Python
response = requests.post(
f"{API_BASE_URL}/api/browser/start",
json={"envId": env_id},
headers=headers
)
debug_port = response.json()["data"]["port"]
```
--------------------------------
### Initialize Browser by IP Address and Port
Source: https://www.drissionpage.cn/tutorials/TgeBrowser
Connect to a browser instance using its IP address and port. This method is useful for remote connections.
```python
page3 = Chromium(f'127.0.0.1:{port}')
print(f"方式3 连接成功: {page3.title}")
```
--------------------------------
### DrissionPage SessionPage: GET Request with Parameters
Source: https://www.drissionpage.cn/SessionPage/visit
Make a GET request with custom headers, cookies, and proxies. The get() method supports various parameters similar to requests.
```python
from DrissionPage import SessionPage
page = SessionPage()
url = 'https://www.baidu.com'
headers = {'referer': 'gitee.com'}
cookies = {'name': 'value'}
proxies = {'http': '127.0.0.1:1080', 'https': '127.0.0.1:1080'}
page.get(url, headers=headers, cookies=cookies, proxies=proxies)
```
--------------------------------
### Initialize SessionPage with Cookies
Source: https://www.drissionpage.cn/SessionPage/settings
Demonstrates initializing SessionPage and setting initial cookies. Use this to pre-populate cookies for a session.
```python
from DrissionPage import SessionPage
page = SessionPage()
page.set.cookies([{'name': 'a', 'value': '1'}, {'name': 'b', 'value': '2'}])
```
--------------------------------
### Initiate Download with Custom Path and Filename
Source: https://www.drissionpage.cn/download/browser
Use the `click.to_download()` method to handle elements that trigger downloads. This method allows specifying a save path and a new filename. If the download is expected to pop up in a new tab, set `new_tab=True`.
```Python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.get('https://im.qq.com/pcqq/index.shtml')
ele = tab('全新体验版下载')
ele.wait.has_rect()
mission = ele.click.to_download(save_path='tmp', rename='QQ.exe')
mission.wait()
```
--------------------------------
### Wait for Download to Begin
Source: https://www.drissionpage.cn/download/browser
Use `wait.download_begin()` to pause execution until a download task starts. This is useful for capturing download information or ensuring a download has initiated before proceeding. The `cancel_it` parameter can be used to cancel the download upon capture.
```Python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab('t:a').click() # Click a link that triggers download
tab.wait.download_begin()
```
--------------------------------
### Browser Object Initialization and Configuration
Source: https://www.drissionpage.cn/browser_control/intro
Shows how to create a Chromium browser object, set global parameters like retry times, and manage the browser lifecycle by quitting.
```Python
from DrissionPage import Chromium
browser = Chromium() # 创建浏览器对象
browser.set.retry_times(10) # 设置整体运行参数
tab = browser.latest_tab # 获取Tab对象
browser.quit() # 关闭浏览器
```
--------------------------------
### Get Active Element on Page
Source: https://www.drissionpage.cn/browser_control/get_elements/find_in_object
Access the active_ele attribute of a page object to get the element that currently has focus on the page.
```python
ele = tab.active_ele
```
--------------------------------
### Create New Browsers with Manual Configuration
Source: https://www.drissionpage.cn/tutorials/functions/new_browser
Manually configure each browser instance with a unique port and user data path using `set_local_port()` and `set_user_data_path()`. This provides granular control over browser environments, ensuring complete isolation.
```python
from DrissionPage import Chromium, ChromiumOptions
co1 = ChromiumOptions().set_local_port(9111).set_user_data_path('data1')
co2 = ChromiumOptions().set_local_port(9222).set_user_data_path('data2')
browser1 = Chromium(co1)
browser2 = Chromium(co2)
```
--------------------------------
### Initialize and Use ChromiumPage
Source: https://www.drissionpage.cn/browser_control/pages
Demonstrates how to initialize ChromiumPage and navigate to a URL. Use this for single-tab browser control.
```Python
from DrissionPage import ChromiumPage
page = ChromiumPage()
page.get('http://DrissionPage.cn')
print(page.title)
```
--------------------------------
### Get Page Title and HTML
Source: https://www.drissionpage.cn/SessionPage/get_page_info
Demonstrates how to get the page title and its HTML content after visiting a URL. Requires importing SessionPage.
```python
from DrissionPage import SessionPage
page = SessionPage()
page.get('http://www.baidu.com')
# 获取页面标题
print(page.title)
# 获取页面html
print(page.html)
```
--------------------------------
### Get Element Attribute
Source: https://www.drissionpage.cn/tutorials/TgeBrowser
Retrieve the value of a specific HTML attribute from a web element. Commonly used to get `href`, `src`, or other attribute values.
```python
# 获取属性
href = page.ele('tag:a').attr('href')
```
--------------------------------
### Create New Browser with Specific Port and Empty User Data Path
Source: https://www.drissionpage.cn/browser_control/connect_browser
Launch a new browser instance by specifying an idle port and an empty user data path. This guarantees a clean browser environment, free from any previous session's data.
```Python
from DrissionPage import Chromium, ChromiumOptions
co = ChromiumOptions().set_local_port(9333).set_user_data_path(r'C:\tmp')
browser = Chromium(co)
```
--------------------------------
### Initialize ChromiumOptions
Source: https://www.drissionpage.cn/browser_control/browser_options
Create a ChromiumOptions object. By default, it reads configurations from an ini file. Set read_file to False to use default settings.
```python
from DrissionPage import ChromiumOptions
co = ChromiumOptions()
```
--------------------------------
### Get Texts of Direct Child Nodes
Source: https://www.drissionpage.cn/SessionPage/get_ele_info
Retrieves a list of texts from the direct child nodes of a SessionElement. Set `text_node_only=True` to get only text nodes.
```python
print(e.texts())
print(e.texts(text_node_only=True))
```
--------------------------------
### Setting Global Options with DrissionPage
Source: https://www.drissionpage.cn/advance/settings
Demonstrates how to set global options like raising exceptions on wait failure and setting the error message language. Supports chained operations for multiple settings.
```python
from DrissionPage.common import Settings
Settings.set_raise_when_wait_failed(True) # Set to raise exception on wait failure
Settings.set_language('en') # Set error messages to English
Settings.set_raise_when_wait_failed(True).set_auto_handle_alert(True) # Chained operation
```
--------------------------------
### DrissionPage SessionPage: GET Request for Local File
Source: https://www.drissionpage.cn/SessionPage/visit
Access local HTML files using the get() method by providing a file path as the URL.
```python
from DrissionPage import SessionPage
page = SessionPage()
page.get(r'D:\demo.html')
```
--------------------------------
### Initialize SessionOptions
Source: https://www.drissionpage.cn/SessionPage/session_opt
Create a SessionOptions object. By default, it reads configurations from an ini file. Set read_file=False to use default configurations.
```python
from DrissionPage import SessionOptions
so = SessionOptions()
```
--------------------------------
### DrissionPage SessionPage: Basic GET Request
Source: https://www.drissionpage.cn/SessionPage/visit
Use the get() method to request a web page. The result is accessed via page attributes like html, not a Response object.
```python
from DrissionPage import SessionPage
page = SessionPage()
page.get('http://g1879.gitee.io/drissionpage')
```
--------------------------------
### Create Browser Environment
Source: https://www.drissionpage.cn/tutorials/TgeBrowser
Use the /api/browser/create endpoint to set up a new browser environment. This includes configuring proxy settings, browser fingerprints, and startup parameters. The response provides an envId for subsequent operations.
```Python
response = requests.post(
f"{API_BASE_URL}/api/browser/create",
json={
"browserName": "自动化测试", # 环境名称
"proxy": {
"protocol": "socks5",
"host": "proxy.example.com",
"port": 8888,
"username": "username",
"password": "password",
},
"fingerprint": {
"os": "Windows",
"platformVersion": 11,
"kernel": "135",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.9.2537 Safari/537.36",
"canvas": True,
"speechVoices": True,
"clientRects": True,
"fonts": ["Arial", "Courier New"],
"disableTLS": [],
"resolution": "1920x1080",
"ram": 8,
"cpu": 4,
"language": "en-US",
"languageBaseIp": True,
"timezone": "Europe/Amsterdam",
"timezoneBaseIp": True,
"hardwareAcceleration": True,
"disableSandbox": False,
"startupParams": "",
"deviceName": "DESKTOP-ABCD",
"portScanProtection": ""
},
"startInfo": {
"startPage": {
"mode": "custom",
"value": [
"https://www.baidu.com"
]
},
"otherConfig": {
"openConfigPage": False,
"checkPage": True,
"extensionTab": True
}
}
},
headers=headers
)
env_id = response.json()["data"]["envId"]
```
--------------------------------
### Manually Open Browser and Take Over via Port
Source: https://www.drissionpage.cn/browser_control/connect_browser
Instructions on how to manually start a browser with remote debugging enabled and then connect to it using the Chromium object. This involves modifying the browser shortcut properties.
```text
"D:\chrome.exe" --remote-debugging-port=9333
```
```Python
from DrissionPage import Chromium
browser = Chromium(9333)
```
--------------------------------
### Get Static Element Version
Source: https://www.drissionpage.cn/browser_control/get_elements/find_in_object
Use s_ele() to get the static version of the first matching element. This is useful for performance optimization when dealing with a large number of elements. It can be called on page or element objects.
```python
from DrissionPage import Chromium
tab = Chromium().latest_tab
# 在页面中查找元素,获取其静态版本
ele1 = tab.s_ele('search text')
# 在动态元素中查找元素,获取其静态版本
ele = tab.ele('search text')
ele2 = ele.s_ele()
# 获取页面元素的静态副本(不传入参数)
s_page = tab.s_ele()
# 获取动态元素的静态副本
s_ele = ele.s_ele()
# 在静态副本中查询下级元素(因为已经是静态元素,用ele()查找结果也是静态)
ele3 = s_page.ele('search text')
ele4 = s_ele.ele('search text')
```
--------------------------------
### Enable/Disable Headless Mode
Source: https://www.drissionpage.cn/browser_control/browser_options
Use `headless()` to control whether the browser starts in headless mode (without a visible UI). If a port is already in use by a non-headless browser, it will be closed before starting the new one.
```python
co.headless(True)
```
--------------------------------
### Wait for Download Start and End
Source: https://www.drissionpage.cn/download/browser
This snippet demonstrates how to wait for a download to begin and then for all download tasks to complete. It's crucial to wait for downloads to finish before attempting to rename files, as filenames are temporary IDs until the download is complete.
```Python
tab = Chromium().latest_tab
tab('#button').click() # Click the download button
tab.wait.download_begin() # Wait for download to start
tab.wait.downloads_done() # Wait for all tasks to end
```
--------------------------------
### Launch Browser
Source: https://www.drissionpage.cn/advance/commands
Launches the browser, waiting for the program to take over. Use the full name `--launch-browser` or the abbreviation `-l`. A port number of 0 uses the value from the configuration file.
```bash
dp --launch-browser 9333
```
```bash
dp -l 0
```
--------------------------------
### Current Y Coordinate Property
Source: https://www.drissionpage.cn/browser_control/actions
Gets the current y-coordinate of the cursor.
```APIDOC
## curr_y
### Description
This property returns the current y-coordinate of the cursor.
### Type
`int`
```
--------------------------------
### Get Tab ID
Source: https://www.drissionpage.cn/browser_control/get_page_info
Retrieve the unique identifier for the current tab.
```python
tab_id = tab.tab_id
```
--------------------------------
### Configure Immediate Exception on Element Not Found
Source: https://www.drissionpage.cn/browser_control/get_elements/behavior
Shows how to set a global configuration to immediately raise an `ElementNotFoundError` when an element is not found. This setting is effective for the entire project once applied.
```Python
from DrissionPage.common import Settings
Settings.set_raise_when_ele_not_found(True)
```
--------------------------------
### Auto-load Default Configuration with Chromium
Source: https://www.drissionpage.cn/advance/ini
This snippet shows the default way to start a Chromium browser instance, which automatically loads configurations from the default INI file.
```python
from DrissionPage import Chromium
browser = Chromium()
```
--------------------------------
### Get Current URL
Source: https://www.drissionpage.cn/browser_control/get_page_info
Retrieve the URL of the current web page.
```python
current_url = tab.url
```
--------------------------------
### Set Chromium Command Line Arguments
Source: https://www.drissionpage.cn/browser_control/browser_options
Examples of setting various Chromium command-line arguments using set_argument(). This includes maximizing the window, setting window size, and opening in guest mode.
```python
# Set to maximize on startup
co.set_argument('--start-maximized')
# Set initial window size
co.set_argument('--window-size', '800,600')
# Open browser in guest mode
co.set_argument('--guest')
```
--------------------------------
### Current X Coordinate Property
Source: https://www.drissionpage.cn/browser_control/actions
Gets the current x-coordinate of the cursor.
```APIDOC
## curr_x
### Description
This property returns the current x-coordinate of the cursor.
### Type
`int`
```
--------------------------------
### Configure SessionPage with SessionOptions
Source: https://www.drissionpage.cn/SessionPage/session_opt
Create a SessionOptions object, configure it with proxies and cookies, and then use it to initialize a SessionPage object.
```python
from DrissionPage import SessionPage, SessionOptions
# Create configuration object (reads from ini file by default)
so = SessionOptions()
# Set proxy
so.set_proxies('http://localhost:1080')
# Set cookies
cookies = ['key1=val1; domain=****', 'key2=val2; domain=****']
so.set_cookies(cookies)
# Create page object with this configuration
page = SessionPage(session_or_options=so)
```
--------------------------------
### Owner Property
Source: https://www.drissionpage.cn/browser_control/actions
Gets the page object associated with this action chain.
```APIDOC
## owner
### Description
This property returns the page object that is using this action chain.
### Type
`ChromiumBase`
```
--------------------------------
### Get All Attributes of an Element
Source: https://www.drissionpage.cn/SessionPage/get_ele_info
Retrieves a dictionary of all attributes and their values for a SessionElement.
```python
print(ele.attrs)
```
--------------------------------
### Initiate File Download with SessionPage
Source: https://www.drissionpage.cn/download/intro
Use the `download()` method to actively start a file download task. This method is available on SessionPage objects and automatically synchronizes cookies.
```python
from DrissionPage import SessionPage
page = SessionPage()
page.download('https://dldir1.qq.com/qqfile/qq/TIM3.4.8/TIM3.4.8.22092.exe')
```
--------------------------------
### Multi-Tab Collaboration Example
Source: https://www.drissionpage.cn/browser_control/tabs
Demonstrates iterating through elements in one tab, opening new tabs for each, extracting information, and closing the new tabs.
```python
from DrissionPage import Chromium
tab = Chromium().latest_tab
tab.get('https://gitee.com/explore/all')
links = tab.eles('t:h3')
for link in links[:-1]:
# Click link and get new tab object
new_tab = link.click.for_new_tab()
# Wait for new tab to load
new_tab.wait.load_start()
# Print tab title
print(new_tab.title)
# Close the newly opened tab
new_tab.close()
```
--------------------------------
### Get Tag Name of an Element
Source: https://www.drissionpage.cn/SessionPage/get_ele_info
Retrieves the tag name of a SessionElement.
```python
print(ele.tag)
```
--------------------------------
### Chainable Configuration
Source: https://www.drissionpage.cn/browser_control/browser_options
Configure browser options using chained method calls for a more concise syntax. Apply these configurations when creating a browser instance.
```APIDOC
## Chainable Operations
### Description
Configure browser options using chained method calls. The `ChromiumOptions` object supports fluent chaining for setting various configurations.
### Example
```python
from DrissionPage import Chromium, ChromiumOptions
# Create options object (reads from ini by default)
co = ChromiumOptions()
# Set to not load images and mute audio, then create browser instance
co.no_imgs(True).mute(True)
page = Chromium(addr_or_opts=co)
# Example with incognito and headless modes
co_advanced = ChromiumOptions()
co_advanced.incognito().headless().set_argument('--no-sandbox')
page_advanced = Chromium(co_advanced)
```
```
--------------------------------
### Get Window Size
Source: https://www.drissionpage.cn/browser_control/get_page_info
Retrieve the dimensions (width, height) of the browser window.
```python
window_width, window_height = tab.rect.window_size
```
--------------------------------
### Switch to Tab (Selenium vs. DrissionPage)
Source: https://www.drissionpage.cn/features/features_demos/selenium
Demonstrates switching to a specific tab using Selenium's window handle management and DrissionPage's latest_tab attribute.
```python
# 使用 selenium:
driver.switch_to.window(driver.window_handles[0])
# 使用 DrissionPage:
tab = browser.latest_tab
```
--------------------------------
### Get User Agent
Source: https://www.drissionpage.cn/browser_control/get_page_info
Retrieve the user agent string of the current page.
```python
user_agent = tab.user_agent
```
--------------------------------
### Get Page Title
Source: https://www.drissionpage.cn/browser_control/get_page_info
Retrieve the title text of the current web page.
```python
page_title = tab.title
```
--------------------------------
### Simulate Ctrl+A Key Combination
Source: https://www.drissionpage.cn/browser_control/actions
Demonstrates how to simulate pressing Ctrl+A to select all text in an input field. Includes a step-by-step method and a more concise chained approach.
```python
from DrissionPage import Chromium
from DrissionPage.common import Keys
# 创建页面对象
tab = Chromium().latest_tab
# 鼠标移动到元素上
tab.actions.move_to('tag:input')
# 点击鼠标,使光标落到元素中
tab.actions.click()
# 按下 ctrl 键
tab.actions.key_down(Keys.CTRL)
# 输入 a
tab.actions.type('a')
# 提起 ctrl 键
tab.actions.key_up(Keys.CTRL)
```
```python
tab.actions.click('tag:input').key_down(Keys.CTRL).type('a').key_up(Keys.CTRL)
```
```python
tab.actions.click('tag:input').type(Keys.CTRL_A)
```
--------------------------------
### Get Element Size
Source: https://www.drissionpage.cn/browser_control/get_ele_info
Retrieves the size of an element as a tuple of (width, height).
```python
size = ele.rect.size
# 返回:(50, 50)
```
--------------------------------
### Monitor Download Progress
Source: https://www.drissionpage.cn/download/browser
Obtain a DownloadMission object to track the status and progress of a browser download. This example shows how to print the download rate in real-time until the mission is complete.
```python
mission = tab.wait.download_begin()
while not mission.is_done:
print(f'\r{mission.rate}%', end='')
```
--------------------------------
### Get All Options
Source: https://www.drissionpage.cn/browser_control/ele_operation
This property returns a list of all option elements within the select element.
```python
all_options = select.select.options
```
--------------------------------
### Page Information
Source: https://www.drissionpage.cn/browser_control/get_page_info
Access properties of the Tab object to get information about the current page.
```APIDOC
## Page Information
### `html`
This property returns the HTML text of the current page.
Note: HTML text does not include the content of `