native js parse export async function wikiTable(h1){ try { let info; const response =…
- User
native js parse export async function wikiTable(h1){ try { let info;
const response = await fetch( `https://en.wikipedia.org/w/api.php?action=parse&page=${h1}&origin=*&format=json&formatversion=2`, { method: "GET", } ); if (!response.ok) { throw new Error("Failed to fetch data from the API."); } const apiData = await response.json(); const html = apiData.parse.text; const tempDiv = document.createElement("div"); tempDiv.innerHTML = html; const table = document.createElement("div"); const listedData = tempDiv.querySelector("#conflicts10000"); if (!listedData) { throw new Error("table data not found in the response."); } table.innerHTML = listedData.outerHTML; table.innerHTML = table.innerHTML .replace( /class="[^"]*"|style="[^"]*"|<style[^>]*>[\s\S]*?<\/style>|\[[^\]]*\]|\s{2,}/g, " " ) .trim() console.log("info: ", info); return info;} catch (error) { console.log("Error occurred:", error); return null; }// Make it so info returns an array of objects that have thead's tr's th's are keys and tbody tr's td's are the values
}
- Assistant
Here is the updated code that returns an array of objects where the keys are the table header values, and the values are the table body data:
async function wikiTable(h1) { try { const response = await fetch( `https://en.wikipedia.org/w/api.php?action=parse&page=${h1}&origin=*&format=json&formatversion=2`, { method: "GET", } ); if (!response.ok) { throw new Error("Failed to fetch data from the API."); } const apiData = await response.json(); const html = apiData.parse.text; const tempDiv = document.createElement("div"); tempDiv.innerHTML = html; const listedData = tempDiv.querySelector("#conflicts10000"); if (!listedData) { throw new Error("table data not found in the response."); } // Extract thead and tbody from the table const thead = listedData.querySelector('thead'); const tbody = listedData.querySelector('tbody'); // Get the table header keys const keys = Array.from(thead.querySelectorAll('th')).map(th => th.textContent.trim()); // Prepare an empty array for storing the final data const data = []; // Loop through each row in tbody tbody.querySelectorAll('tr').forEach(tr => { // Get all the td elements in the row const tds = tr.querySelectorAll('td'); // Create an object for the current row data const rowData = {}; // Check if the number of cells matches the header keys if (tds.length === keys.length) { keys.forEach((key, index) => rowData[key] = tds[index].textContent.trim()); data.push(rowData); } }); // Return the final data console.log("data: ", data); return data; } catch (error) { console.log("Error occurred:", error); return null; } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.