我如何从网站复制文本并在我自己的HTML文件中使用它

How can I copy text from a website and use it in my own HTML file

本文关键字:文件 HTML 自己的 我自己 网站 复制 文本      更新时间:2023-09-26

我正在制作一个网站来查找航班的价格。每次我加载我的HTML文件,我必须复制价格从另一个网站,不是我的,并插入到我的HTML文件。

另一个网站的源代码表明,我正在寻找的标签是一个span标签,如<span class="amount price-amount">250</span>

所以问题是:我如何复制或提取信息,并使用它或插入它在我的HTML文件?

我想解决它使用HTML, CSS, JavaScript和/或Bootstrap。

客户端web抓取

您可以使用页面剥离来完成此操作。至少我是这么说的。一个基本的例子是:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        var doc = document.createElement('div');
        doc.innerHTML = xhr.responseText;
        var elems = doc.getElementsByTagName('*'),
        prices = [];
        for (var i = 0; i < elems.length; i += 1) {
            if ((elems[i].getAttribute('class')||'').indexOf('price-amount') > -1 && (elems[i].getAttribute('class')||'').indexOf('amount') > -1) {
                prices.push(elems[i].innerHTML);
            }
        }
    }
};
xhr.open('GET', 'airlinesite.com/path/to/page', true);
xhr.send();

这将从airlinesite.com/path/to/page获取HTML。然后它会得到所有的元素。循环遍历它们。如果它有一个类amountprice-amount,它将把它的值存储在一个数组中。这些值将存储在prices中。

为此,目标域必须具有CORS,它可能具有CORS

使用web-scraper;我推荐requestcheerio。这假设您有Node JS并且知道如何安装包。下面是一个简单的示例代码:

var request = require('request');
var cheerio = require('cheerio');
request(this.url, function(error, response, body) {
    if (!error && response.statusCode == 200) {
        // body is the scraped html
        $ = cheerio.load(arg); // the jQuery-like selector
        var price = $('span.price-amount').text(); // the price you want. Use the selector accordingly.
    }
}

使用inspect element,通过右键单击并单击inspect element来实现。然后会有一个带箭头的方框指向左上角,这就是搜索点击吧。然后选择页面上你想要的部分,然后它就会加载它,这样你就可以复制粘贴它了