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

如何从外部网页获取指定数据或部分HTML并在自有HTML页面展示?

Hey there! Let's break down how to tackle both of your requirements—grabbing specific text from an external page's source and inserting chunks of external HTML on button click. I'll walk you through practical, working examples, plus cover the critical cross-domain gotcha you'll run into.


1. Fetching Specific Text from External Page's Tags

To pull text content from a specific HTML tag on an external page, we'll use the Fetch API to grab the page source, then parse it with DOMParser to target the element we want.

Example Code:

<!-- Your HTML -->
<div class="text-container">
  <p>Loaded text will appear here:</p>
  <span id="target-text"></span>
</div>

<script>
// Function to fetch and extract text
async function fetchSpecificText() {
  try {
    // Fetch the external page source
    const response = await fetch('https://external-page-url.com');
    if (!response.ok) throw new Error('Failed to fetch page');
    
    // Convert response to raw HTML text
    const html = await response.text();
    
    // Parse HTML into a DOM we can query
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    
    // Target the specific tag (e.g., a <h1> with class "page-title")
    const targetElement = doc.querySelector('h1.page-title');
    
    // Insert the text into your page
    if (targetElement) {
      document.getElementById('target-text').textContent = targetElement.textContent;
    } else {
      document.getElementById('target-text').textContent = 'Target element not found';
    }
  } catch (error) {
    console.error('Error:', error);
    document.getElementById('target-text').textContent = 'Failed to load content';
  }
}

// Run the function on page load (or trigger via button click)
fetchSpecificText();
</script>

2. Inserting External HTML Chunk on Button Click

For inserting a portion of an external page's HTML when a user clicks a button, we'll use a similar approach—but instead of extracting text, we'll inject the raw HTML chunk directly into your page.

Example Code:

<!-- Your HTML -->
<button id="load-html-btn">Load External HTML</button>
<div id="html-container"></div>

<script>
// Add click listener to the button
document.getElementById('load-html-btn').addEventListener('click', async () => {
  try {
    const response = await fetch('https://external-page-url.com');
    if (!response.ok) throw new Error('Failed to fetch page');
    
    const html = await response.text();
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    
    // Target the chunk you want (e.g., a <section> with id "featured-content")
    const htmlChunk = doc.querySelector('section#featured-content');
    
    if (htmlChunk) {
      // Insert the HTML chunk into your container
      document.getElementById('html-container').innerHTML = htmlChunk.outerHTML;
    } else {
      document.getElementById('html-container').textContent = 'Target HTML chunk not found';
    }
  } catch (error) {
    console.error('Error:', error);
    document.getElementById('html-container').textContent = 'Failed to load HTML';
  }
});
</script>

Important Notes: Cross-Domain Restrictions

Big heads-up: Browsers enforce the Same-Origin Policy, which means your frontend code can't directly fetch content from a different domain unless that domain explicitly allows it via CORS (Cross-Origin Resource Sharing) headers.

If you hit a CORS error, here's how to fix it:

  • Use a backend proxy: Create a simple server-side script (e.g., Node.js, PHP) that fetches the external content on your behalf, then serve it to your frontend. Since server-side code isn't bound by browser CORS rules, this works seamlessly.
  • Check if the external site has an API: Some sites offer APIs to retrieve content without scraping HTML—this is always a better, more reliable option if available.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:50:27