You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Selenium WebDriver的JavascriptExecutor获取script标签中strokeText内容

Solution to Extract strokeText Content from Canvas Script

To get the text used in the strokeText call from the script tag that draws the canvas, you can use Selenium's JavascriptExecutor to scan the page's script elements and parse the relevant content. Here's how to do it:

Step-by-Step Explanation

  1. Access all script elements: Use JavaScript to retrieve every <script> tag on the page.
  2. Find the relevant script: Look for the script that contains the strokeText function call (since this is the one responsible for drawing the canvas text).
  3. Extract the text argument: Parse the function call to pull out the string passed to strokeText (the "Answer: XXXXX" part).

Java Code Example

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class CanvasTextExtractor {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("http://the-internet.herokuapp.com/challenging_dom");

        // Execute JavaScript to extract the strokeText content
        JavascriptExecutor js = (JavascriptExecutor) driver;
        String strokeText = (String) js.executeScript("""
            const scripts = document.getElementsByTagName('script');
            for (let script of scripts) {
                const content = script.textContent;
                if (content.includes('strokeText')) {
                    const strokeCall = content.split('strokeText(')[1];
                    if (strokeCall) {
                        const argsPart = strokeCall.split(')')[0];
                        const textArg = argsPart.split(',')[0].trim();
                        return textArg.replace(/^['"]|['"]$/g, '');
                    }
                }
            }
            return null;
        """);

        System.out.println("Extracted strokeText content: " + strokeText);
        driver.quit();
    }
}

Python Code Example

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://the-internet.herokuapp.com/challenging_dom")

# JavaScript snippet to extract the strokeText content
js_script = """
const scripts = document.getElementsByTagName('script');
for (let script of scripts) {
    const content = script.textContent;
    if (content.includes('strokeText')) {
        const strokeCall = content.split('strokeText(')[1];
        if (strokeCall) {
            const argsPart = strokeCall.split(')')[0];
            const textArg = argsPart.split(',')[0].trim();
            return textArg.replace(/^['"]|['"]$/g, '');
        }
    }
}
return null;
"""

stroke_text = driver.execute_script(js_script)
print(f"Extracted strokeText content: {stroke_text}")

driver.quit()

Notes

  • Wait for page load: If the script loads asynchronously, add a wait (like WebDriverWait in Java/Python) to ensure the page is fully loaded before executing the script.
  • Robust parsing: The code handles both single and double quotes around the text argument, and ignores any whitespace, making it resilient to minor changes in the script format.

内容的提问来源于stack exchange,提问作者MohitChouhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:01:25