如何获取TChromiumDevTools元素标签页中的文本?
Absolutely, this is totally doable! The reason idHttp.Get(url) falls short here is that it only grabs the raw, initial HTML source from the server. But the Elements Tab in DevTools shows the live, modified DOM after JavaScript has run, updated elements, or loaded dynamic content. To get that exact text, you’ll want to use the Chrome DevTools Protocol (CDP)—the same tool the browser uses to power the Elements Tab itself.
If you’re working in Delphi, CEF4Delphi (a robust Chromium wrapper for Delphi) makes this straightforward. Here’s how to approach it:
Step 1: Set Up CEF4Delphi
First, integrate CEF4Delphi into your Delphi project. It provides all the components needed to embed a Chromium instance and communicate directly via CDP.
Step 2: Communicate via the DevTools Protocol
CDP works by sending JSON-formatted commands to the Chromium browser. The key commands you’ll need are:
DOM.getDocument: Fetches the root node of the live DOM treeDOM.querySelector: Finds a specific element using a CSS selector (just like you would in the Elements Tab’s search bar)DOM.getInnerText: Retrieves the text content of a targeted element using its node ID
Step 3: Example Delphi Code Snippet
Here’s a simplified example of how to send these commands with CEF4Delphi:
procedure TMainForm.FetchElementText; var LGetDocCmd: TJSONObject; begin // First, send a command to get the root DOM node LGetDocCmd := TJSONObject.Create; try LGetDocCmd.AddPair('id', TJSONNumber.Create(1)); LGetDocCmd.AddPair('method', 'DOM.getDocument'); LGetDocCmd.AddPair('params', TJSONObject.Create); // Send the command to the Chromium instance Chromium1.Browser.MainFrame.ExecuteDevToolsMethod(LGetDocCmd); finally LGetDocCmd.Free; end; // Next, in the DevTools response handler, you'd: // 1. Extract the root node ID from the response // 2. Send a DOM.querySelector command to find your target element (e.g., by CSS selector) // 3. Use the resulting node ID to call DOM.getInnerText and retrieve the text end;
Step 4: Handle Asynchronous Responses
CDP uses asynchronous messaging, so you’ll need to set up an event handler in CEF4Delphi to listen for responses from the browser. When you receive the response to your initial DOM.getDocument command, you can chain the subsequent commands to target your element and fetch its text.
Alternative: Headless Chromium
If you don’t need a visible browser window, you can run Chromium in headless mode and connect to its CDP WebSocket endpoint. This is perfect for automated scraping tasks where you just need the live DOM text without a UI.
This approach will capture exactly the same text you see in the Elements Tab—including any dynamic content added or modified by JavaScript, which idHttp can’t access.
内容的提问来源于stack exchange,提问作者Ago

