Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/clis/jd/item.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest';
import { getRegistry } from '../../registry.js';
import './item.js';

describe('jd item adapter', () => {
const command = getRegistry().get('jd/item');

it('registers the command with correct shape', () => {
expect(command).toBeDefined();
expect(command!.site).toBe('jd');
expect(command!.name).toBe('item');
expect(command!.domain).toBe('item.jd.com');
expect(command!.strategy).toBe('cookie');
expect(typeof command!.func).toBe('function');
});

it('has sku as a required positional arg', () => {
const skuArg = command!.args.find((a) => a.name === 'sku');
expect(skuArg).toBeDefined();
expect(skuArg!.required).toBe(true);
expect(skuArg!.positional).toBe(true);
});

it('has images arg with default 10', () => {
const imagesArg = command!.args.find((a) => a.name === 'images');
expect(imagesArg).toBeDefined();
expect(imagesArg!.default).toBe(10);
});

it('includes expected columns', () => {
expect(command!.columns).toEqual(
expect.arrayContaining(['title', 'price', 'shop', 'specs', 'mainImages', 'detailImages']),
);
});
});
101 changes: 101 additions & 0 deletions src/clis/jd/item.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/**
* 京东商品详情 — browser cookie, DOM scraping + evaluate.
*
* 依赖: 需要在 Chrome 已登录京东
* 用法: opencli jd item 100291143898
*/
import { cli, Strategy } from '../../registry.js';

cli({
site: 'jd',
name: 'item',
description: '京东商品详情(价格、主图、详情图、规格参数)',
domain: 'item.jd.com',
strategy: Strategy.COOKIE,
args: [
{
name: 'sku',
required: true,
positional: true,
help: '商品 SKU ID(如 100291143898)',
},
{
name: 'images',
type: 'int',
default: 10,
help: '详情图数量(默认10)',
},
],
columns: ['title', 'price', 'shop', 'specs', 'mainImages', 'detailImages'],
func: async (page, kwargs) => {
const sku = kwargs.sku;
const maxImages = kwargs.images as number;
const url = `https://item.jd.com/${sku}.html`;

await page.goto(url, { waitUntil: 'load' });
await page.wait(2);

// 滚动加载详情图
for (let i = 0; i < 6; i++) {
await page.evaluate(`window.scrollTo(0, ${i * 2500})`);
await page.wait(1);
}
await page.evaluate(`window.scrollTo(0, document.body.scrollHeight)`);
await page.wait(2);

const data = await page.evaluate(`
(() => {
const maxImg = ${maxImages};
// 尝试多种价格选择器
const skuMatch = location.pathname.match(/(\\d+)\\.html/);
const sku = skuMatch ? skuMatch[1] : '';
const priceEl = document.querySelector('.J-p-' + sku) ||
document.querySelector('[class*="price"] [class*="num"]') ||
document.querySelector('.p-price strong') ||
document.querySelector('.price.jd-price');
const price = priceEl?.textContent?.trim() || 'not found';

// 标题
const title = document.querySelector('.product-title')?.textContent?.trim() ||
document.title.split('-')[0].trim();

// 店铺
const shop = document.querySelector('.J-shop-name')?.textContent?.trim() || '京东自营';

// 所有图片
const allImgs = Array.from(document.querySelectorAll('img[src*="360buyimg.com"]'));
const srcs = allImgs.map(img => img.src).filter(Boolean);
const unique = [...new Set(srcs)];

// 主图
const mainImgs = unique
.filter(u => u.includes('/n1/') || u.includes('/n3/') || u.includes('/n4/') || u.includes('/img/'))
.slice(0, maxImg);

// 详情图
const detailImgs = unique
.filter(u => u.includes('/babel/') || u.includes('/popshop/'))
.slice(0, maxImg);

// 规格参数:从页面文本提取
const text = document.body.innerText;
const specMatch = text.match(/商品编号[\\s\\S]*?(?=包装清单|\\n\\n|$)/);
let specs = {};
if (specMatch) {
const lines = specMatch[0].split('\\n').filter(l => l.trim());
for (let i = 0; i < lines.length - 1; i += 2) {
const key = lines[i].trim();
const val = lines[i + 1]?.trim() || '';
if (key && val && key !== '商品编号') {
specs[key] = val;
}
}
}

return { title, price, shop, specs, mainImages: mainImgs, detailImages: detailImgs, totalImages: unique.length };
})()
`);

return [data];
},
});