### Create ChromiumPage Object Source: https://context7.com/g1879/drissionpage/llms.txt Instantiate a ChromiumPage object to control Chromium-based browsers. This is the simplest way to start browser automation. ```python from DrissionPage import ChromiumPage # Simplest way to create a page object page = ChromiumPage() # Visit a webpage page.get('https://www.baidu.com') # Get page title print(page.title) # Get page URL print(page.url) # Get page HTML print(page.html) # Close the browser page.quit() ``` -------------------------------- ### Use GET and POST Requests Source: https://context7.com/g1879/drissionpage/llms.txt Utilize SessionPage and WebPage's s mode for sending HTTP requests with built-in auto-retry and encoding recognition. Supports various request types and configurations. ```python from DrissionPage import SessionPage page = SessionPage() # GET request page.get('https://api.example.com/users') print(page.response.status_code) # Status code print(page.json) # Auto-parsed JSON response # POST request - send form data data = {'username': 'admin', 'password': '123456'} page.post('https://api.example.com/login', data=data) # POST request - send JSON data page.post('https://api.example.com/users', json={'name': 'John', 'age': 30}) # Set request headers and proxy page.get('https://api.example.com', headers={'User-Agent': 'Mozilla/5.0'}, proxies={'http': '127.0.0.1:7890'}) # Read local HTML file page.get(r'D:\demo.html') ``` -------------------------------- ### Get Element Information Source: https://context7.com/g1879/drissionpage/llms.txt Extract various attributes and states of a web element. Ensure the element is available before accessing its properties. ```python print(ele.inner_html) ``` ```python print(ele.html) ``` ```python href = ele.attr('href') class_name = ele.attr('class') ``` ```python attrs = ele.attrs ``` ```python print(ele.tag) ``` ```python print(ele.rect.location) # 吀癸 print(ele.rect.size) # 大小 print(ele.rect.midpoint) # 中心点 ``` ```python print(ele.states.is_displayed) # 是否可见 print(ele.states.is_enabled) # 是否可用 print(ele.states.is_checked) # 是否选中 print(ele.states.is_in_viewport) # 是否在视口内 ``` ```python print(ele.css_path) ``` ```python print(ele.xpath) ``` -------------------------------- ### Get Element Information Source: https://context7.com/g1879/drissionpage/llms.txt Retrieve various information from element objects, including text content, attributes, position, and size. ```python from DrissionPage import ChromiumPage page = ChromiumPage() page.get('https://www.example.com') ele = page.ele('#main') # Get text content print(ele.text) ``` -------------------------------- ### Network Listening Source: https://context7.com/g1879/drissionpage/llms.txt Capture network requests and responses to retrieve API data or wait for specific network events. Listeners can be started, stopped, and configured for specific URLs. ```python from DrissionPage import ChromiumPage page = ChromiumPage() # 启动监听器,指定要捕捉的 URL 特征 page.listen.start('api/data') # 访问网页 page.get('https://www.example.com') # 等待并荷取数据包 packet = page.listen.wait() print(packet.url) # 请求 URL print(packet.method) # 请求方法 print(packet.request.postData) # 请求数据 print(packet.response.body) # 响应内容 print(packet.response.headers) # 响应头 # 循环荷取多个数据包 page.listen.start('api/') for i in range(5): page.ele('@rel=next').click() res = page.listen.wait() print(res.response.body) # 使用迷代器实时荷取 page.listen.start('gitee.com/explore') page.get('https://gitee.com/explore/all') for packet in page.listen.steps(): print(packet.url) page('@rel=next').click() # 等待所有请求完成 page.listen.wait_silent(timeout=10) # 停止监听 page.listen.stop() ``` -------------------------------- ### Configure Browser with ChromiumOptions Source: https://context7.com/g1879/drissionpage/llms.txt Use ChromiumOptions to set browser startup parameters like path, port, proxy, and headless mode before creating a ChromiumPage object. ```python from DrissionPage import ChromiumPage, ChromiumOptions # Create configuration object co = ChromiumOptions() # Set browser path co.set_browser_path('/usr/bin/google-chrome') # Set port co.set_local_port(9333) # Set headless mode co.headless() # Set proxy co.set_proxy('http://127.0.0.1:7890') # Disable image loading to improve speed co.no_imgs() # Set window size co.set_argument('--window-size', '1920,1080') # Create page object with configuration page = ChromiumPage(addr_or_opts=co) page.get('https://www.example.com') ``` -------------------------------- ### Set Download Path Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Specifies the default path where downloaded files will be saved. ```python so.set_download_path(path='str or Path') ``` -------------------------------- ### Session Options Configuration Methods Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Methods for configuring various aspects of the HTTP session. ```APIDOC ## POST /api/users ### Description This method is used to set whether to verify SSL certificate. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **on_off** (bool) - Required - `bool` indicates on or off ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself ``` ```APIDOC ## POST /api/users/adapter ### Description This method is used to add an adapter. ### Method POST ### Endpoint /api/users/adapter ### Parameters #### Query Parameters - **url** (str) - Required - Adapter corresponding url - **adapter** (HTTPAdapter) - Required - Adapter object ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself ``` ```APIDOC ## POST /api/users/stream ### Description This method is used to set whether to use streaming response content. ### Method POST ### Endpoint /api/users/stream ### Parameters #### Query Parameters - **on_off** (bool) - Required - `bool` indicates on or off ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself ``` ```APIDOC ## POST /api/users/trust_env ### Description This method is used to set whether to trust the environment. ### Method POST ### Endpoint /api/users/trust_env ### Parameters #### Query Parameters - **on_off** (bool) - Required - `bool` indicates on or off ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself ``` ```APIDOC ## POST /api/users/max_redirects ### Description This method is used to set the maximum number of redirects. ### Method POST ### Endpoint /api/users/max_redirects ### Parameters #### Query Parameters - **times** (int) - Required - Maximum number of redirects ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself ``` -------------------------------- ### set.verify() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Configures whether to verify SSL certificates. ```APIDOC ## `set.verify()` ### Description This method is used to set whether to verify the SSL certificate. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters #### Request Body - **on_off** (bool) - Required - `bool` indicates on or off ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### Set SSL Client Certificate Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Configures the SSL client certificate. Provide the path to the certificate file in PEM format or a ('cert', 'key') tuple. ```python so.set_cert(cert='str or tuple') ``` -------------------------------- ### set_cert() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets the path of the SSL client certificate file or a ('cert', 'key') tuple. ```APIDOC ## POST /set_cert ### Description Sets the path of the SSL client certificate file (.pem format) or ('cert', 'key') tuple. ### Method POST ### Endpoint /set_cert ### Parameters #### Request Body - **cert** (str | tuple) - Required - Certificate path or tuple. ### Request Example ```json { "cert": "/path/to/client.pem" } ``` ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself. #### Response Example ```json { "message": "Certificate set successfully" } ``` ``` -------------------------------- ### set_auth() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets authentication tuple information. ```APIDOC ## POST /set_auth ### Description Sets authentication tuple information. ### Method POST ### Endpoint /set_auth ### Parameters #### Request Body - **auth** (tuple | HTTPBasicAuth) - Required - Authentication tuple or object. ### Request Example ```json { "auth": ["username", "password"] } ``` ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself. #### Response Example ```json { "message": "Authentication set successfully" } ``` ``` -------------------------------- ### Save Current Settings to File Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Saves the current session configuration to an ini file. Pass a path to save to a specific file, or omit it to save to the currently read configuration file. Note that 'hooks' and 'adapters' configurations are not saved. ```python so.save() ``` ```python so.save(path=r'D:\tmp\settings.ini') ``` -------------------------------- ### Save Settings to File Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Methods for saving session configurations to ini files. ```APIDOC ## POST /api/settings/save ### Description This method is used to save configuration items to an ini file. ### Method POST ### Endpoint /api/settings/save ### Parameters #### Query Parameters - **path** (str, Path) - Optional - The path of the ini file, pass `None` to save to the currently read configuration file ### Response #### Success Response (200) - **str** - Absolute path of the saved ini file ### Request Example ```python # Save the currently read ini file so.save() # Save current configuration to a specified path so.save(path=r'D:\tmp\settings.ini') ``` ``` ```APIDOC ## POST /api/settings/save_to_default ### Description This method is used to save configuration items to a fixed default ini file. The default ini file refers to the one built-in with DrissionPage. ### Method POST ### Endpoint /api/settings/save_to_default ### Parameters No parameters. ### Response #### Success Response (200) - **str** - Absolute path of the saved ini file ### Request Example ```python so.save_to_default() ``` ``` -------------------------------- ### Create WebPage Object Source: https://context7.com/g1879/drissionpage/llms.txt Instantiate a WebPage object that combines ChromiumPage and SessionPage functionalities, allowing seamless switching between browser (d) and packet (s) modes. ```python from DrissionPage import WebPage # Create object, defaults to d mode (browser mode) page = WebPage() # Create in s mode (packet mode) page = WebPage('s') # Visit webpage page.get('https://www.example.com') # Switch to s mode page.change_mode() # Switch to d mode page.change_mode('d') # Get current mode print(page.mode) # 'd' or 's' ``` -------------------------------- ### Set Proxy for Session Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Configures proxy settings for the session. Provide the HTTP proxy address. If the HTTPS proxy is not specified, it defaults to the HTTP proxy. ```python so.set_proxies('http://127.0.0.1:1080') ``` -------------------------------- ### set.trust_env() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Configures whether to trust environment variables for proxy settings. ```APIDOC ## `set.trust_env()` ### Description This method is used to set whether to trust the environment. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters #### Request Body - **on_off** (bool) - Required - `bool` to represent on or off ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### set_proxies() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets proxy information for HTTP and HTTPS. ```APIDOC ## POST /set_proxies ### Description Sets proxy information. ### Method POST ### Endpoint /set_proxies ### Parameters #### Request Body - **http** (str) - Required - HTTP proxy address. - **https** (str) - Optional - HTTPS proxy address. If None, the value of `http` parameter is used. ### Request Example ```json { "http": "http://127.0.0.1:1080" } ``` ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself. #### Response Example ```json { "message": "Proxies set successfully" } ``` ``` -------------------------------- ### set.add_adapter() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Adds a custom adapter for handling specific URL requests. ```APIDOC ## `set.add_adapter()` ### Description This method is used to add an adapter. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters #### Request Body - **url** (str) - Required - URL corresponding to the adapter - **adapter** (HTTPAdapter) - Required - Adapter object ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### set_download_path() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets the default download save path. ```APIDOC ## POST /set_download_path ### Description Sets the default download save path. ### Method POST ### Endpoint /set_download_path ### Parameters #### Request Body - **path** (str | Path) - Required - Default download save path. ### Request Example ```json { "path": "/path/to/downloads" } ``` ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself. #### Response Example ```json { "message": "Download path set successfully" } ``` ``` -------------------------------- ### Waiting Mechanisms Source: https://context7.com/g1879/drissionpage/llms.txt Provides various methods for waiting, ensuring operations are performed at the correct time. This includes waiting for elements to appear, disappear, be deleted, or load, as well as waiting for URL or title changes, document loading, new tabs, or downloads. A simple time-based wait is also available. ```python from DrissionPage import ChromiumPage page = ChromiumPage() page.get('https://www.example.com') # 等待元素出现 ele = page.ele('#dynamic', timeout=10) # 显式等待元素 page.wait.ele_displayed('#loading') page.wait.ele_hidden('#loading') page.wait.ele_deleted('#temp') page.wait.ele_loaded('#content') # 等待 URL 变化 page.wait.url_change('dashboard') # 等待标题变化 page.wait.title_change('New Title') # 等待页面加载完成 page.wait.doc_loaded() # 等待新标签页出现 tab_id = page.wait.new_tab() # 等待下载开始 mission = page.wait.download_begin() # 等待指定秒数 page.wait(3) # 元素等待 ele = page.ele('#btn') ele.wait.displayed() ele.wait.hidden() ele.wait.deleted() ele.wait.stop_moving() ``` -------------------------------- ### set.cert() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Sets the SSL client certificate for secure connections. ```APIDOC ## `set.cert()` ### Description This method is used to set the SSL client certificate. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters #### Request Body - **cert** (str or Tuple[str, str]) - Required - Path to the SSL client certificate file (.pem format), or a tuple of ('cert', 'key') ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### Create SessionPage Object Source: https://context7.com/g1879/drissionpage/llms.txt Instantiate a SessionPage object for efficient data packet sending and receiving without browser control. It is based on the requests library. ```python from DrissionPage import SessionPage, SessionOptions # Simplest way to create page = SessionPage() # Create with configuration so = SessionOptions() so.set_proxies(http='127.0.0.1:7890') so.set_retry(times=5, interval=2) page = SessionPage(session_or_options=so) # Send GET request page.get('https://www.baidu.com') print(page.html) # Send request with parameters page.get('https://api.example.com', headers={'Authorization': 'Bearer token'}, cookies={'session': 'abc123'}) ``` -------------------------------- ### Set Query Parameters Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Adds query parameters to the request URL. The 'params' argument should be a dictionary. ```python so.set_params(params='dict') ``` -------------------------------- ### Action Chains for Complex Operations Source: https://context7.com/g1879/drissionpage/llms.txt Execute complex mouse and keyboard operations using action chains, supporting chained calls and immediate execution. Includes actions like moving, clicking, typing, and dragging. ```python from DrissionPage import ChromiumPage from DrissionPage.common import Actions, Keys page = ChromiumPage() page.get('https://www.example.com') # 使用内置 actions 属性 page.actions.move_to('#kw').click().type('DrissionPage') # 创建独立的 Actions 对象 ac = Actions(page) # 鼠标移动 ac.move_to('#element') # 移动到元素 ac.move_to((300, 400)) # 移动到坐标 ac.move(100, 50) # 相对移动 # 鼠标点击 ac.click('#button') # 左键点击 ac.r_click('#menu') # 右键点击 ac.db_click('#item') # 双击 # 拖拽操作 ac.hold('#draggable') # 按住 ac.move(300, 0) # 移动 ac.release() # 释放 # 键盘输入 ac.type('Hello World') ac.type((Keys.CTRL, 'a')) # Ctrl+A ac.key_down(Keys.SHIFT) ac.type('abc') ac.key_up(Keys.SHIFT) # 链式调用示例 ac.move_to('#input').click().type('text').key_down(Keys.ENTER) # 等待 ac.wait(2) # 等待 2 秒 # 渐折 ac.scroll(0, 300, on_ele='#container') ``` -------------------------------- ### Set Retry Options Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Configures the number of retries and the interval between retries when a connection times out. 'times' is the number of retries, and 'interval' is the time in seconds between attempts. ```python so.set_retry(times=int, interval=float) ``` -------------------------------- ### ChromiumElement Methods and Properties Source: https://github.com/g1879/drissionpage/blob/master/docs_en/whatsnew/3_2.md Methods and properties for interacting with and querying individual elements on a Chromium page. ```APIDOC ## ChromiumElement Methods and Properties ### Description Provides access to element locations, states, and actions. ### Properties - **locations.screen_location**: Gets the coordinates of the top-left corner of the element on the screen. - **locations.screen_midpoint**: Gets the coordinates of the midpoint of the element on the screen. - **locations.screen_click_point**: Gets the coordinates of the click point of the element on the screen. - **locations.click_point**: Gets the coordinates of the click point of the element on the page. - **locations.viewport_click_point**: Gets the coordinates of the click point of the element on the viewport. - **states.is_covered**: Gets whether the element is covered. ### Methods - **click.at()**: Clicks on the element with an offset, specified key optional. - **wait.covered()**: Waits for the element to be covered. - **wait.covered()**: Waits for the element to not be covered. ``` -------------------------------- ### Save Settings to Default Ini File Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Saves the current session configuration to the default ini file built into DrissionPage. This method takes no parameters. ```python so.save_to_default() ``` -------------------------------- ### File Download Management Source: https://context7.com/g1879/drissionpage/llms.txt Supports file downloads using either the browser's download manager or an internal downloader. You can set the download path and filename, initiate downloads, wait for them to complete, and retrieve download information. Downloads can also be cancelled. ```python from DrissionPage import ChromiumPage page = ChromiumPage() page.get('https://www.example.com/download') # 设置下载路径 page.set.download_path('./downloads') # 设置下载文件名 page.set.download_file_name('my_file') # 点击下载按钮 page.ele('#download-btn').click() # 等待下载开始并获取任务对象 mission = page.wait.download_begin() # 等待下载完成 mission.wait() # 获取下载信息 print(mission.path) # 文件路径 print(mission.name) # 文件名 print(mission.progress) # 下载进度 # 取消下载 mission.cancel() ``` -------------------------------- ### Handle Browser Alerts Source: https://context7.com/g1879/drissionpage/llms.txt Handles browser alerts by accepting them and returning their text content. The `handle_alert` method has a timeout parameter to specify how long to wait for the alert. ```python txt = page.handle_alert(timeout=10) ``` ```python has_alert = page.states.has_alert ``` -------------------------------- ### set.params() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Sets the query parameter dictionary for requests. ```APIDOC ## `set.params()` ### Description This method is used to set query parameter dictionary. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters #### Request Body - **params** (dict) - Required - Query parameter dictionary ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### Set Callback Hooks Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Configures callback methods to be executed at specific points in the request lifecycle. The 'hooks' parameter should be a dictionary. ```python so.set_hooks(hooks='dict') ``` -------------------------------- ### set_params() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets query parameters. ```APIDOC ## POST /set_params ### Description Sets query parameters. ### Method POST ### Endpoint /set_params ### Parameters #### Request Body - **params** (dict) - Required - Query parameter dictionary. ### Request Example ```json { "params": { "key1": "value1", "key2": "value2" } } ``` ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself. #### Response Example ```json { "message": "Parameters set successfully" } ``` ``` -------------------------------- ### SessionOptions Properties Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Properties to access various session configuration settings. ```APIDOC ## GET /api/session/headers ### Description This property returns the headers configuration. ### Method GET ### Endpoint /api/session/headers ### Response #### Success Response (200) - **dict** - The headers configuration ``` ```APIDOC ## GET /api/session/cookies ### Description This property returns the cookies configuration in a `list` format. ### Method GET ### Endpoint /api/session/cookies ### Response #### Success Response (200) - **list** - The cookies configuration ``` ```APIDOC ## GET /api/session/proxies ### Description This property returns the proxy configuration. ### Method GET ### Endpoint /api/session/proxies ### Response #### Success Response (200) - **dict** - The proxy configuration in the format `{'http': 'http://xx.xx.xx.xx:xxxx', 'https': 'http://xx.xx.xx.xx:xxxx'}` ``` ```APIDOC ## GET /api/session/auth ### Description This property returns the authentication configuration. ### Method GET ### Endpoint /api/session/auth ### Response #### Success Response (200) - **tuple, HTTPBasicAuth** - The authentication configuration ``` ```APIDOC ## GET /api/session/hooks ### Description This property returns the callback methods configuration. ### Method GET ### Endpoint /api/session/hooks ### Response #### Success Response (200) - **dict** - The callback methods configuration ``` ```APIDOC ## GET /api/session/params ### Description This property returns the query parameters configuration. ### Method GET ### Endpoint /api/session/params ### Response #### Success Response (200) - **dict** - The query parameters configuration ``` ```APIDOC ## GET /api/session/verify ### Description This property returns the SSL certificate verification configuration. ### Method GET ### Endpoint /api/session/verify ### Response #### Success Response (200) - **bool** - The SSL certificate verification configuration ``` ```APIDOC ## GET /api/session/cert ### Description This property returns the SSL certificate configuration. ### Method GET ### Endpoint /api/session/cert ### Response #### Success Response (200) - **str, tuple** - The SSL certificate configuration ``` ```APIDOC ## GET /api/session/adapters ### Description This property returns the adapter configuration. ### Method GET ### Endpoint /api/session/adapters ### Response #### Success Response (200) - **List[HTTPAdapter]** - The adapter configuration ``` ```APIDOC ## GET /api/session/stream ### Description This property returns the streaming response configuration. ### Method GET ### Endpoint /api/session/stream ### Response #### Success Response (200) - **bool** - The streaming response configuration ``` ```APIDOC ## GET /api/session/trust_env ### Description This property returns the trust environment configuration. ### Method GET ### Endpoint /api/session/trust_env ### Response #### Success Response (200) - **bool** - The trust environment configuration ``` ```APIDOC ## GET /api/session/max_redirects ### Description This property returns the `max_redirects` configuration. ### Method GET ### Endpoint /api/session/max_redirects ### Response #### Success Response (200) - **int** - The `max_redirects` configuration ``` ```APIDOC ## GET /api/session/timeout ### Description This property returns the connection timeout configuration. ### Method GET ### Endpoint /api/session/timeout ### Response #### Success Response (200) - **int, float** - The connection timeout configuration ``` ```APIDOC ## GET /api/session/download_path ### Description This property returns the default download path configuration. ### Method GET ### Endpoint /api/session/download_path ### Response #### Success Response (200) - **str** - The default download path configuration ``` -------------------------------- ### Set Authentication Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets authentication credentials for the session. Accepts a tuple or an HTTPBasicAuth object. ```python so.set_auth(auth='tuple or HTTPBasicAuth') ``` -------------------------------- ### Set Cookies for Session Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Use this method to set cookie information. Each setting will overwrite all previously set cookie information. Accepts a list of strings, a list/tuple of tuples, a string, or a dictionary. ```python cookies = ['key1=val1; domain=xxxx', 'key2=val2; domain=xxxx'] so.set_cookies(cookies) ``` -------------------------------- ### Manage Cookies and Cache Source: https://context7.com/g1879/drissionpage/llms.txt Manages browser cookies, localStorage, sessionStorage, and cache. Cookies can be set using dictionaries or string formats, and removed individually or cleared entirely. localStorage and sessionStorage items can be set and deleted. ```python from DrissionPage import ChromiumPage page = ChromiumPage() page.get('https://www.example.com') # 获取所有 cookies cookies = page.cookies() # 设置 cookies page.set.cookies({'name': 'value', 'domain': '.example.com'}) page.set.cookies('name=value; domain=.example.com') page.set.cookies([{'name': 'n1', 'value': 'v1'}, {'name': 'n2', 'value': 'v2'}]) # 删除单个 cookie page.remove_cookies('cookie_name') # 清除所有 cookies page.clear_cookies() # 操作 localStorage page.set.local_storage('key', 'value') page.set.local_storage('key', False) # 删除 # 操作 sessionStorage page.set.session_storage('key', 'value') # 清除缓存 page.clear_cache() # 清除所有 page.clear_cache(cookies=False) # 保留 cookies ``` -------------------------------- ### set_hooks() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets callback methods. ```APIDOC ## POST /set_hooks ### Description Sets callback methods. ### Method POST ### Endpoint /set_hooks ### Parameters #### Request Body - **hooks** (dict) - Required - Callback method dictionary. ### Request Example ```json { "hooks": { "response": [ "my_callback_function" ] } } ``` ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself. #### Response Example ```json { "message": "Hooks set successfully" } ``` ``` -------------------------------- ### release() - Release Left Mouse Button Source: https://github.com/g1879/drissionpage/blob/master/docs_en/ChromiumPage/actions.md Simulates releasing the left mouse button. This action can be performed after moving to an element. ```APIDOC ## POST /actions/release ### Description Simulates releasing the left mouse button. This action can be performed after moving to a specific element. ### Method POST ### Endpoint /actions/release ### Parameters #### Request Body - **on_ele** (ChromiumElement | str) - Optional - The element object or text locator to release the button on. If not provided, the release will occur at the current mouse position. ### Response #### Success Response (200) - **Actions** (object) - The action chain object itself, allowing for method chaining. #### Response Example ```json { "message": "Release action performed successfully" } ``` ``` -------------------------------- ### Screenshot Functionality Source: https://context7.com/g1879/drissionpage/llms.txt Provides capabilities for taking screenshots of the entire page, specific elements, or the current viewport. Screenshots can be saved to files, specified paths, or retrieved as base64 encoded strings. Options include full-page screenshots and scrolling elements into view before capturing. ```python from DrissionPage import ChromiumPage page = ChromiumPage() page.get('https://www.example.com') # 页面截图 page.get_screenshot('./page.png') # 整页截图(包括视口外部分) page.get_screenshot('./full_page.png', full_page=True) # 指定保存路径 page.get_screenshot(path='./screenshots', name='test.png') # 元素截图 ele = page.ele('#main') ele.get_screenshot('./element.png') # 滚动到中心后截图 ele.get_screenshot('./center.png', scroll_to_center=True) # 获取 base64 格式 base64_str = page.get_screenshot(as_base64=True) ``` -------------------------------- ### ChromiumPage Methods and Properties Source: https://github.com/g1879/drissionpage/blob/master/docs_en/whatsnew/3_2.md Methods and properties available on the ChromiumPage object for interacting with a Chromium-based browser. ```APIDOC ## ChromiumPage Methods and Properties ### Description Provides methods and properties for controlling and querying the state of a Chromium browser page. ### Methods - **run_cdp_loaded()**: Executes CDP command, waits for page load to complete before executing. - **run_js_loaded()**: Executes JS statement, waits for page load to complete before executing. - **remove_ele()**: Removes an element from the page. - **get_frame()**: Gets a `ChromiumFrame` object. ### Properties - **wait.load_complete()**: Waits for page to finish loading. - **wait.upload_paths_inputted()**: Waits for file paths to be entered into the file selection box. - **rect.browser_location**: Gets the coordinates of the top-left corner of the browser on the screen. - **rect.page_location**: Gets the coordinates of the top-left corner of the page on the screen. - **rect.viewport_location**: Gets the coordinates of the viewport on the screen. - **rect.browser_size**: Gets the size of the browser. - **rect.page_size**: Gets the size of the page. - **rect.viewport_size**: Gets the size of the viewport without the scrollbar. - **rect.viewport_size_with_scrollbar**: Gets the size of the viewport with the scrollbar. ``` -------------------------------- ### Element Finding Methods ele() and eles() Source: https://context7.com/g1879/drissionpage/llms.txt Use `ele()` to find a single element and `eles()` to find all matching elements. Supports various locating syntaxes including ID, class, attribute, text, tag, CSS selectors, and XPath. ```python from DrissionPage import ChromiumPage page = ChromiumPage() page.get('https://www.example.com') # Find by ID (# prefix) ele = page.ele('#username') # Find by class (. prefix) ele = page.ele('.btn-primary') # Find by attribute (@ prefix) ele = page.ele('@name=email') ele = page.ele('@type=submit') # Find by text content ele = page.ele('text=登录') # Exact match ele = page.ele('text:登录') # Fuzzy match ele = page.ele('登录') # Default fuzzy match # Find by tag name ele = page.ele('tag:div') ele = page.ele('tag:input@type=password') # Multiple attribute match (AND with @@) ele = page.ele('@@class=btn@@name=submit') # Multiple attribute match (OR with @|) ele = page.ele('@|id=login@|id=signin') # Attribute negation (@!) ele = page.ele('@!disabled') # CSS selector ele = page.ele('css:div.container > p') # XPath ele = page.ele('xpath://div[@id="main"]/p') # Find all matching elements eles = page.eles('tag:a') for e in eles: print(e.text, e.attr('href')) # Use index to find the Nth element ele = page.ele('tag:li', index=3) # The 3rd li element ``` -------------------------------- ### Perform a double-click on an element Source: https://github.com/g1879/drissionpage/blob/master/docs_en/ChromiumPage/actions.md Use `db_click()` to simulate a double-left-click. It can be called after moving to a specific element. -------------------------------- ### r_release() - Release Right Mouse Button Source: https://github.com/g1879/drissionpage/blob/master/docs_en/ChromiumPage/actions.md Simulates releasing the right mouse button. This action can be performed after moving to an element. ```APIDOC ## POST /actions/r_release ### Description Simulates releasing the right mouse button. This action can be performed after moving to a specific element. ### Method POST ### Endpoint /actions/r_release ### Parameters #### Request Body - **on_ele** (ChromiumElement | str) - Optional - The element object or text locator to release the button on. If not provided, the release will occur at the current mouse position. ### Response #### Success Response (200) - **Actions** (object) - The action chain object itself, allowing for method chaining. #### Response Example ```json { "message": "Right release action performed successfully" } ``` ``` -------------------------------- ### SessionPage Methods Source: https://github.com/g1879/drissionpage/blob/master/docs_en/whatsnew/3_2.md Additional setting methods provided by the SessionPage object for configuring session-specific options. ```APIDOC ## SessionPage Methods ### Description Methods for configuring various session-related settings. ### Methods - **set.header()**: Sets a header value. - **set.proxies()**: Sets proxies. - **set.auth()**: Sets login information. - **set.hooks()**: Sets callback methods. - **set.params()**: Sets connection parameters. - **set.cert()**: Sets a certificate. - **set.stream()**: Sets whether to use streaming response content. - **set.trust_env()**: Sets whether to trust the environment. - **set.max_redirects()**: Sets the maximum number of redirects. - **set.max_redirects()**: Adds an adapter. ``` -------------------------------- ### close() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Closes the current connection or session. ```APIDOC ## `close()` ### Description This method is used to close the connection. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters **Parameters:** None ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### db_click() - Double Click Left Mouse Button Source: https://github.com/g1879/drissionpage/blob/master/docs_en/ChromiumPage/actions.md Simulates a double-click of the left mouse button. This action can be performed after moving to a specific element. ```APIDOC ## POST /actions/db_click ### Description Simulates a double-click of the left mouse button on an element or at a specified location. ### Method POST ### Endpoint /actions/db_click ### Parameters #### Request Body - **on_ele** (ChromiumElement | str) - Optional - The element object or text locator to double-click on. If not provided, the click will occur at the current mouse position. ### Response #### Success Response (200) - **Actions** (object) - The action chain object itself, allowing for method chaining. #### Response Example ```json { "message": "Double click action performed successfully" } ``` ``` -------------------------------- ### set.max_redirects() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Sets the maximum number of redirects allowed for a request. ```APIDOC ## `set.max_redirects()` ### Description This method is used to set the maximum number of redirects. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters #### Request Body - **times** (int) - Required - Maximum number of redirects ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### Tab Management Source: https://context7.com/g1879/drissionpage/llms.txt Manage multiple browser tabs simultaneously without explicit focus switching. New tabs, windows, and incognito contexts can be created. ```python from DrissionPage import ChromiumPage page = ChromiumPage() page.get('https://www.example.com') # 获取所有标签页 ID print(page.tab_ids) # 创建新标签页 tab = page.new_tab('https://www.google.com') # 获取标签页对象 tab1 = page.get_tab(0) # 按索引 tab2 = page.get_tab(page.tab_ids[1]) # 按 ID # 在新标签页中操作 tab.get('https://www.baidu.com') tab.ele('#kw').input('test') # 创建新窗口 new_window = page.new_tab(new_window=True) # 创建隐身窗口 incognito = page.new_tab(new_context=True) # 关闭标签页 tab.close() # 激活标签页 tab.set.activate() ``` -------------------------------- ### set.stream() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Enables or disables streaming response content. ```APIDOC ## `set.stream()` ### Description This method is used to set whether to use streaming response content. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters #### Request Body - **on_off** (bool) - Required - `bool` to represent on or off ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### Page Navigation and Control Source: https://context7.com/g1879/drissionpage/llms.txt Control browser navigation, including going back, forward, refreshing, and stopping page loads. Page load modes and timeouts can be configured. ```python from DrissionPage import ChromiumPage page = ChromiumPage() # 访问网页 page.get('https://www.example.com') # 后退 page.back() page.back(2) # 后退 2 步 # 前进 page.forward() # 刷新页面 page.refresh() page.refresh(ignore_cache=True) # 倈略缓刷新 # 停止加载 page.stop_loading() # 页面渐折 page.scroll.to_top() # 渐折到顶部 page.scroll.to_bottom() # 渐折到底部 page.scroll.down(300) # 向下渐折 300 像素 page.scroll.up(200) # 向上渐折 200 像素 page.scroll.to_location(0, 500) # 渐折到指定位置 # 渐折到元素可见 page.scroll.to_see('#footer') # 设置页面加载策略 page.set.load_mode.eager() # 等待 DOM 加载完成 page.set.load_mode.none() # 不等待 # 设置超时时间 page.set.timeouts(base=30, page_load=60) # 设置窗口大小 page.set.window.max() # 最大化 page.set.window.mini() # 最小化 page.set.window.size(1200, 800) # 指定大小 ``` -------------------------------- ### set.hooks() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/set_session.md Sets callback functions for specific events. ```APIDOC ## `set.hooks()` ### Description This method is used to set callback functions. ### Method Not specified (likely a method call on a configuration object) ### Endpoint Not applicable (this is a library method) ### Parameters #### Request Body - **hooks** (dict) - Required - Callback functions ### Response #### Success Response (200) - **None** (None) - Returns None #### Response Example ```json null ``` ``` -------------------------------- ### set_cookies() Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets cookie information. Each setting overwrites all previously set cookie information. ```APIDOC ## POST /set_cookies ### Description Sets cookie information. Each setting will overwrite all previously set cookie information. ### Method POST ### Endpoint /set_cookies ### Parameters #### Request Body - **cookies** (RequestsCookieJar | list | tuple | str | dict) - Required - Cookies to set. ### Request Example ```json { "cookies": ["key1=val1; domain=xxxx", "key2=val2; domain=xxxx"] } ``` ### Response #### Success Response (200) - **SessionOptions** (object) - The configuration object itself. #### Response Example ```json { "message": "Cookies set successfully" } ``` ``` -------------------------------- ### Execute JavaScript Source: https://context7.com/g1879/drissionpage/llms.txt Executes JavaScript code within the browser context, either on the page or on specific elements. It supports returning values, passing arguments, and executing asynchronous JavaScript. CDP commands can also be run. ```python from DrissionPage import ChromiumPage page = ChromiumPage() page.get('https://www.example.com') # 执行 JS 并获取返回值 result = page.run_js('return document.title;') print(result) # 传递参数 page.run_js('alert(arguments[0] + arguments[1]);', 'Hello', ' World') # 在元素上执行 JS ele = page.ele('#box') height = ele.run_js('return this.offsetHeight;') # 异步执行 JS page.run_async_js('setTimeout(() => console.log("done"), 1000);') # 等待页面加载完成后执行 page.run_js_loaded('return document.readyState;') # 执行 CDP 命令 page.run_cdp('Page.stopLoading') page.run_cdp('Network.enable') ``` -------------------------------- ### m_release() - Release Middle Mouse Button Source: https://github.com/g1879/drissionpage/blob/master/docs_en/ChromiumPage/actions.md Simulates releasing the middle mouse button. This action can be performed after moving to an element. ```APIDOC ## POST /actions/m_release ### Description Simulates releasing the middle mouse button. This action can be performed after moving to a specific element. ### Method POST ### Endpoint /actions/m_release ### Parameters #### Request Body - **on_ele** (ChromiumElement | str) - Optional - The element object or text locator to release the button on. If not provided, the release will occur at the current mouse position. ### Response #### Success Response (200) - **Actions** (object) - The action chain object itself, allowing for method chaining. #### Response Example ```json { "message": "Middle release action performed successfully" } ``` ``` -------------------------------- ### DrissionPage Exceptions Source: https://github.com/g1879/drissionpage/blob/master/docs_en/whatsnew/3_2.md This section details the custom exceptions provided by DrissionPage to handle specific error scenarios during web automation. ```APIDOC ## DrissionPage Exceptions ### Description Custom exceptions used in DrissionPage to indicate specific error conditions during web automation. ### Exception List - **AlertExistsError**: Throws if there is an unhandled alert when calling page functions. - **ContextLossError**: Throws if elements are called after the page is refreshed. - **ElementLossError**: Throws if elements become invalid due to page or self refreshing. - **CallMethodError**: Throws if there is an exception when calling CDP. - **TabClosedError**: Throws if the tab is closed and its functions are still called. - **ElementNotFoundError**: Throws if an element cannot be found. - **JavaScriptError**: Throws if there is a JavaScript runtime error. - **NoRectError**: Throws if there is no size or location information for an element. ``` -------------------------------- ### Set Connection Timeout Source: https://github.com/g1879/drissionpage/blob/master/docs_en/SessionPage/session_options.md Sets the connection timeout attribute. Specify the waiting time in seconds. ```python so.set_timeout(float) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.