以下是一个简单的前端爬虫代码示例,使用的是JavaScript语言:
// 引入axios库,用于发起HTTP请求
const axios = require('axios');
// 引入cheerio库,用于解析HTML
const cheerio = require('cheerio');
// 定义需要爬取的网页URL
const url = 'https://example.com';
// 发起GET请求,获取网页内容
axios.get(url)
.then(response => {
// 使用cheerio加载网页内容
const $ = cheerio.load(response.data);
// 使用CSS选择器获取需要的信息
const title = $('title').text();
const description = $('meta[name="description"]').attr('content');
// 打印爬取到的信息
console.log('Title:', title);
console.log('Description:', description);
})
.catch(error => {
// 处理请求失败的情况
console.error('Error:', error);
});
上述代码使用axios库发起GET请求获取网页内容,然后使用cheerio库解析HTML。通过使用CSS选择器,我们可以获取到所需的信息,如网页标题(<title>
元素的内容)和描述(<meta name="description">
元素的content
属性值)。最后,将获取到的信息打印到控制台。
以下是一个使用Java语言编写的简单爬虫代码示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class WebCrawler {
public static void main(String[] args) throws IOException {
// 目标网页的URL
String urlString = "https://example.com";
URL url = new URL(urlString);
// 使用 BufferedReader 读取网页内容
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuilder content