2024-08-16

以下是一个使用Python实现的简单示例,使用requests库直接爬取网页上的酒店信息,不需要解析或处理JavaScript加密。




import requests
from bs4 import BeautifulSoup
 
# 目标网址
url = 'https://www.example.com/hotel-info'
 
# 发送HTTP请求
response = requests.get(url)
 
# 检查请求是否成功
if response.status_code == 200:
    # 使用BeautifulSoup解析网页内容
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 提取酒店信息
    hotel_info = soup.find('div', id='hotel-info')
    
    # 打印酒店信息
    print(hotel_info.text.strip())
else:
    print("Failed to retrieve data from the server")

请注意,这个示例假定网页上直接就有酒店信息,并且没有通过JavaScript动态加载。如果实际情况中网站采取了反爬措施,如JavaScript加密内容,那么可能需要更复杂的处理,例如分析JavaScript代码、使用Selenium等工具来运行JavaScript并提取信息。

2024-08-16

在JavaScript中生成PDF文件,可以使用jsPDF库。以下是一个简单的例子,展示如何使用jsPDF库生成PDF并下载:

首先,确保你已经在项目中引入了jsPDF库。你可以通过npm安装它:




npm install jspdf

然后,你可以使用以下代码生成并下载PDF:




import jsPDF from 'jspdf';
 
// 创建一个新的jsPDF实例
const pdf = new jsPDF();
 
// 添加文本到PDF
pdf.text('Hello world!', 10, 10);
 
// 添加更多内容...
 
// 下载PDF文件
pdf.save('download.pdf');

这段代码创建了一个包含文本"Hello world!"的PDF文件,并将其保存为"download.pdf"。如果你想添加更复杂的内容,比如图片或者表格,jsPDF库也提供了相应的方法。

2024-08-16

使用SheetJS导出树形结构的数据到XLSX文件,你可以先将树形结构转换为平面表格形式,然后使用SheetJS的XLSX.utils.aoa_to_sheet方法生成工作表,最后通过XLSX.write方法导出文件。以下是一个简单的实现示例:




const XLSX = require('xlsx');
 
// 假设你有一个树形结构的数据
const treeData = [
  {
    id: 1,
    name: 'Node 1',
    children: [
      { id: 2, name: 'Child 1' },
      { id: 3, name: 'Child 2' },
    ],
  },
  {
    id: 4,
    name: 'Node 2',
    children: [
      { id: 5, name: 'Child 3' },
      { id: 6, name: 'Child 4' },
    ],
  },
];
 
function flattenTree(tree, level = 0) {
  return tree.reduce((acc, node) => {
    const row = [node.name]; // 根据需要,你可以添加更多列
    acc.push(row);
    if (node.children && node.children.length > 0) {
      acc = acc.concat(flattenTree(node.children, level + 1).map(childRow => [...row, ...childRow]));
    }
    return acc;
  }, []);
}
 
function exportToXLSX(tree, fileName) {
  const headers = ['Name']; // 根据你的树形结构,定义表头
  const data = flattenTree(tree);
  const ws = XLSX.utils.aoa_to_sheet([headers, ...data]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  
  XLSX.writeFile(wb, fileName);
}
 
exportToXLSX(treeData, 'treeData.xlsx');

这段代码首先定义了一个flattenTree函数,该函数递归地将树形结构转换为一个平面数组。然后定义了一个exportToXLSX函数,该函数接受树形结构数据和文件名作为参数,并将其导出为XLSX文件。

确保你已经安装了SheetJS:




npm install xlsx

运行上述代码后,你将得到一个名为treeData.xlsx的文件,其中包含了树形结构数据的平面表示。

2024-08-16

在JavaScript中,有三种常用的方法来计算代码执行的时间:

  1. 使用Date对象
  2. 使用performance.now()
  3. 使用console.time()console.timeEnd()

以下是每种方法的示例代码:

  1. 使用Date对象:



let startTime = new Date(); // 代码执行前
// ... 要计算执行时间的代码
// ...
let endTime = new Date(); // 代码执行后
let executionTime = endTime - startTime; // 计算执行时间
console.log(`执行时间: ${executionTime} 毫秒`);
  1. 使用performance.now()



let startTime = performance.now(); // 代码执行前
// ... 要计算执行时间的代码
// ...
let endTime = performance.now(); // 代码执行后
let executionTime = endTime - startTime; // 计算执行时间
console.log(`执行时间: ${executionTime} 微秒`);
  1. 使用console.time()console.timeEnd()



console.time('计时器'); // 代码执行前
// ... 要计算执行时间的代码
// ...
console.timeEnd('计时器'); // 代码执行后
// 控制台将输出名为 '计时器' 的计时器结果

这三种方法都可以用来计算代码的执行时间,但是console.time()console.timeEnd()是最简单和最直观的方法。

2024-08-16

Fabric.js 是一个用于在网页上绘制图形、文本、图片的 JavaScript 库。以下是使用 Fabric.js 绘制不同图形的示例代码:




// 引入Fabric.js库
fabric.isLikelyNode = typeof process !== 'undefined';
if (fabric.isLikelyNode) {
  fabric = global.fabric || require('fabric').fabric;
} else {
  fabric = window.fabric;
}
 
// 创建一个新的Canvas实例
var canvas = new fabric.Canvas('c');
 
// 绘制一个矩形
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  width: 50,
  height: 50,
  fill: 'blue'
});
canvas.add(rect);
 
// 绘制一个圆形
var circle = new fabric.Circle({
  radius: 25,
  left: 150,
  top: 150,
  fill: 'green'
});
canvas.add(circle);
 
// 绘制一条直线
var line = new fabric.Line([100, 200, 200, 100], {
  fill: 'black',
  stroke: 'red',
  strokeWidth: 3
});
canvas.add(line);
 
// 绘制一个三角形
var triangle = new fabric.Triangle({
  width: 100,
  height: 100,
  left: 300,
  top: 50,
  fill: 'yellow'
});
canvas.add(triangle);
 
// 绘制一个文本
var text = new fabric.Text('Hello Fabric!', {
  left: 150,
  top: 200,
  fontSize: 40,
  fill: 'purple'
});
canvas.add(text);
 
// 绘制一个图像
fabric.Image.fromURL('https://example.com/image.png', function(img) {
  img.set({
    left: 50,
    top: 50,
    width: 100,
    height: 100
  });
  canvas.add(img);
});

这段代码展示了如何使用 Fabric.js 绘制矩形、圆形、直线、三角形、文本和图像。每个图形都可以通过设置不同的属性来定制样式和位置。通过这个指南,开发者可以快速了解并使用 Fabric.js 的绘图功能。

2024-08-16



// 引入pinyin-pro库
const { pinyin } = require('pinyin-pro');
 
// 使用pinyin-pro库将汉字转换为拼音
const chineseToPinyin = (chinese) => {
  return pinyin(chinese, { toneType: 'none' }); // 不包含声调
};
 
// 使用pinyin-pro库将汉字转换为拼音首字母
const chineseToPinyinInitials = (chinese) => {
  return pinyin(chinese, {
    style: pinyin.STYLE_NORMAL, // 设置输出格式为普通格式
    segment: true // 开启多音字拆分
  }).map(word => word.map(pinyin => pinyin[0]).join('')).join('');
};
 
// 测试函数
const test = () => {
  const chinese = '中文';
  console.log(chineseToPinyin(chinese)); // 输出: ['zhi1', 'wen2']
  console.log(chineseToPinyinInitials(chinese)); // 输出: zw
};
 
// 调用测试函数
test();

这段代码演示了如何使用pinyin-pro库来将汉字转换为拼音以及拼音的首字母。首先引入库,然后定义两个函数,一个用于转换拼音,一个用于转换拼音首字母。最后,我们定义了一个测试函数来测试这两个转换函数,并打印出转换结果。

2024-08-16



// 创建表格的函数
function createTable(data) {
    // 获取body元素
    const body = document.body;
 
    // 创建表格
    const table = document.createElement('table');
    table.border = 1;
 
    // 创建表头
    const thead = document.createElement('thead');
    const headerRow = document.createElement('tr');
    data[0].forEach((header) => {
        const th = document.createElement('th');
        th.innerText = header;
        headerRow.appendChild(th);
    });
    thead.appendChild(headerRow);
    table.appendChild(thead);
 
    // 创建表身
    const tbody = document.createElement('tbody');
    data.forEach((rowData, rowIndex) => {
        const row = document.createElement('tr');
        rowData.forEach((cellData) => {
            const cell = document.createElement('td');
            cell.innerText = cellData;
            row.appendChild(cell);
        });
        tbody.appendChild(row);
    });
    table.appendChild(tbody);
 
    // 将表格添加到body中
    body.appendChild(table);
}
 
// 示例数据
const sampleData = [
    ['Name', 'Age', 'Country'],
    ['Alice', 25, 'USA'],
    ['Bob', 30, 'UK'],
    // ...更多数据
];
 
// 调用函数创建表格
createTable(sampleData);

这段代码展示了如何使用JavaScript动态创建一个简单的HTML表格。首先,我们定义了一个createTable函数,它接受一个数组作为参数,该数组代表表格的数据。函数内部,我们使用DOM操作创建了tabletheadtbody等元素,并填充了相应的数据。最后,我们将表格添加到页面的body元素中。这个例子简单明了,展示了如何使用JavaScript处理表格数据并创建交互式表格。

2024-08-16



import * as THREE from 'three';
import { CSS2DRenderer, CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { vue } from 'vue/types/vue';
 
// 假设你已经有了一个Vue组件,并且在其中有一个three.js场景(scene)和渲染器(renderer)
export default {
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      labelRenderer: null,
      model: null
    };
  },
  mounted() {
    this.initScene();
    this.initCamera();
    this.initRenderers();
    this.initListeners();
    this.loadModel();
    this.animate();
  },
  methods: {
    initScene() {
      this.scene = new THREE.Scene();
    },
    initCamera() {
      this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      this.camera.position.z = 5;
    },
    initRenderers() {
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.renderer.setClearColor(0xffffff);
      document.body.appendChild(this.renderer.domElement);
 
      this.labelRenderer = new CSS2DRenderer();
      this.labelRenderer.setSize(window.innerWidth, window.innerHeight);
      this.labelRenderer.domElement.style.position = 'absolute';
      this.labelRenderer.domElement.style.top = 0;
      document.body.appendChild(this.labelRenderer.domElement);
 
      // 创建OrbitControls来控制相机旋转
      new OrbitControls(this.camera, this.renderer.domElement);
    },
    initListeners() {
      window.addEventListener('resize', this.onWindowResize, false);
    },
    onWindowResize() {
      this.camera.aspect = window.innerWidth / window.innerHeight;
      this.camera.updateProjectionMatrix();
 
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.labelRenderer.setSize(window.innerWidth, window.innerHeight);
    },
    loadModel() {
      const loader = new GLTFLoader();
      loader.load('path/to/your/model.gltf', (gltf) => {
        this.model = gltf.scene;
        this.scene.add(this.model);
 
        // 假设模型有几何信息,并且你想要添加标签
        this.model.traverse((child) => {
          if (child.isMesh) {
            // 创建CSS2DObject作为标签
            const label = document.createElement('div');
            label.className = 'label';
2024-08-16

在网页中,如果想要截取一个iframe的内容并将其转换为图片,可以使用HTML5 Canvas和JavaScript来实现。以下是一个简单的示例代码:




<!DOCTYPE html>
<html>
<body>
 
<iframe id="myframe" src="youriframecontent.html" onload="captureIframe()"></iframe>
 
<script>
function captureIframe() {
    var iframe = document.getElementById('myframe');
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
 
    // 设置 canvas 大小
    canvas.width = iframe.offsetWidth;
    canvas.height = iframe.offsetHeight;
 
    // 将 iframe 内容绘制到 canvas 上
    var iframeImg = new Image();
    iframeImg.onload = function() {
        ctx.drawImage(iframeImg, 0, 0, canvas.width, canvas.height);
 
        // 下载或者显示 canvas 内容
        var imgData = canvas.toDataURL('image/png');
        var img = document.createElement('img');
        img.src = imgData;
 
        document.body.appendChild(img);
    };
 
    // 由于同源策略,需要确保 iframe 内容有CORS头支持
    iframeImg.crossOrigin = 'Anonymous';
    iframeImg.src = iframe.contentWindow.location.href;
}
</script>
 
</body>
</html>

请注意,由于同源策略(Same-origin policy),如果iframe的内容来自一个不同的域(domain),那么你需要确保该内容服务器发送了正确的CORS头部,允许跨域资源共享。如果没有这些头部,你将无法通过Canvas API获取到iframe内容的图片。

2024-08-16

在JavaScript中,可以使用Canvas元素来压缩图片。以下是一个简单的函数,用于压缩图片并返回一个新的图片URL:




function compressImage(src, quality, maxWidth, callback) {
  const img = new Image();
  img.src = src;
  img.onload = function () {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const width = img.width > maxWidth ? maxWidth : img.width;
    const height = (width / img.width) * img.height;
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(img, 0, 0, width, height);
    const newDataUrl = canvas.toDataURL('image/jpeg', quality);
    callback(newDataUrl);
  };
}
 
// 使用示例
compressImage('path/to/your/image.jpg', 0.7, 800, function(compressedImageUrl) {
  console.log('Compressed image URL:', compressedImageUrl);
  // 可以将compressedImageUrl设置为img元素的src或用于上传等
});

这个函数接受图片路径、压缩质量和最大宽度作为参数,并在图片加载完成后进行压缩。压缩完成后,会调用回调函数并传入新的图片URL。