我正在尝试从网页中提取数据或数字,然后按一下按钮将其导出到 csv 文件。这是我正在使用的代码,但当您单击按钮时它不会执行任何操作。如果可能的话,希望有人能帮助我解决这个问题。或者有没有其他方法可以实现这一点。
请更改网页,因为我已经用我的测试过了。提前非常感谢您。
// ==UserScript==
// @name Extract and Export Data
// @namespace http://your-website.com
// @version 1.0
// @description Extract data and export to CSV
// @author Your Name
// @match *://*/*
// @grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
// Function to extract the number before "Data1 and Data2"
function extractData() {
const textContent = document.body.textContent || document.body.innerText;
const match = /(\d+)\s*Data1\s*and\s*Data2/i.exec(textContent);
const extractedNumber = match && match[1] ? match[1] : '';
return extractedNumber;
}
// Function to export data to CSV
function exportToCSV(data) {
const csvContent = 'data:text/csv;charset=utf-8,' + encodeURIComponent(data);
const link = document.createElement('a');
link.href = csvContent;
link.target = '_blank';
link.download = 'exported_data.csv';
link.click();
}
// Function to handle the button click
function handleClick() {
const extractedNumber = extractData();
if (extractedNumber) {
// Example: You can customize the CSV format based on your needs
const csvData = `Number Before Data1 and Data2\n${extractedNumber}`;
// Trigger the CSV export
exportToCSV(csvData);
} else {
console.error('Data extraction failed. Check the page structure.');
}
}
// Create a button and append it to the page
const button = document.createElement('button');
button.textContent = 'Export Data to CSV';
button.addEventListener('click', handleClick);
// You can customize the button's style here
GM_addStyle(`
button {
background-color: #4CAF50;
color: white;
padding: 10px;
font-size: 16px;
cursor: pointer;
}
`);
// Append the button to the body of the webpage
document.body.appendChild(button);
})();
确保您的用户脚本环境(如 Tampermonkey、Greasemonkey 等)已正确设置,并且脚本已正确安装并在您的目标网页上运行。