如何用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
- Access all script elements: Use JavaScript to retrieve every
<script>tag on the page. - Find the relevant script: Look for the script that contains the
strokeTextfunction call (since this is the one responsible for drawing the canvas text). - 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
WebDriverWaitin 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
相关产品推荐
相关产品推荐

