新手求助:使用CasperJS获取SVG元素d属性失败
Extracting SVG Path
d Attribute with CasperJS Hey there! Let's work through this issue you're having—since you're new to JavaScript/PhantomJS/CasperJS, it's totally normal to hit snags with element selection and async timing. Let's break down what's going wrong and fix your code step by step.
First, Let's Diagnose the Common Issues in Your Original Code
- Incorrect Wait Timing: Your
this.wait(6000)is inside thethenOpencallback, which doesn't properly chain into CasperJS's step queue. This means Casper might try to extract data before the page (or elements) are fully loaded. - Using
getElementsAttributeWhen You Need a Single Value: This method returns an array of attributes. If you're targeting one specificpath[6], you should usegetElementAttributeinstead to get a single string value. - Redundant XPath Calls: You don't need to call
require('casper').selectXPathevery time—define it once at the top for cleaner code. - No Fallback for Missing Elements: Your code doesn't handle cases where the target element isn't found, making it hard to debug.
Fixed Code with Explanations
Here's a revised version of your script that addresses all these issues, plus adds better error handling:
var casper = require('casper').create({ pageSettings: { loadImages: true, loadPlugins: true, userAgent: "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36" } }); // Define XPath helper once var x = require('casper').selectXPath; // File system module (define once for reuse) var fs = require('fs'); // Start by opening your local HTML file—double-check the path! // For Windows, it should look like: file:///C:/Your/Full/Path/baidu.html casper.start("file:///path/to/baidu.html", function() { console.log("Local page opened successfully"); }); // Wait for the target SVG path to exist (more reliable than fixed wait time) casper.waitForSelector(x('//*[@id="trend"]/svg/path[6]'), function() { console.log("Target SVG path element found"); // Get the single 'd' attribute value var pathData = this.getElementAttribute(x('//*[@id="trend"]/svg/path[6]'), 'd'); if (pathData) { this.echo("Extracted path data: " + pathData); // Write to file—make sure you have write permissions in this directory fs.write("data_graph.txt", pathData, 'w'); this.echo("Data saved to data_graph.txt"); } else { this.echo("Warning: The 'd' attribute is empty for this element"); } }, function() { // Timeout callback if element never loads this.echo("Error: Timed out waiting for the target SVG path"); }, 10000); // Wait up to 10 seconds casper.run();
Additional Debugging Tips
- Verify Your Selector: Open your saved
baidu.htmlin a browser, right-click the target path element, and use "Inspect" to confirm:- The XPath
//*[@id="trend"]/svg/path[6]actually points to the element you want (browser dev tools let you test XPaths in the console). - The element has a non-empty
dattribute.
- The XPath
- Try CSS Selectors: If XPath is giving you trouble, use a CSS selector instead. For example:
casper.waitForSelector('#trend svg path:nth-child(6)', function() { var pathData = this.getElementAttribute('#trend svg path:nth-child(6)', 'd'); // ... rest of the code }); - Check File Paths: Ensure your local HTML path is correctly formatted (especially on Windows, use forward slashes or escaped backslashes). Also, make sure you're running the script from a directory where you have permission to write files.
内容的提问来源于stack exchange,提问作者Romain
相关产品推荐
相关产品推荐

