摘要:代购独立站的核心功能是让用户粘贴商品链接后自动抓取标题、价格、SKU等信息。本文讲解如何使用HttpClient + Jsoup + 正则表达式实现稳定采集,并引入异步任务队列防止阻塞。Taoify跨境电商的商品采集模块每日处理百万级链接,架构值得借鉴。
一、采集流程设计
当用户在Taoify跨境电商独立站前台粘贴淘宝或1688链接后,系统需要完成以下步骤:链接解析提取商品ID→调用平台API或模拟请求获取HTML→解析HTML提取结构化数据→映射到内部商品模型→异步保存到数据库。
二、淘宝商品采集实现(基于官方API)
推荐优先使用官方API,稳定且无需反爬。首先申请淘宝开放平台AppKey,然后调用taobao.item.get接口。
java
@Servicepublic class TaobaoProductCollector { @Autowired private RestTemplate restTemplate; public ProductInfo collect(String url) { // 从URL中提取商品ID String pattern = "id=(\d+)"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(url); String itemId = m.find() ? m.group(1) : null; // 构建API请求 String apiUrl = "https://eco.taobao.com/router/rest"; Map params = new HashMap<>(); params.put("method", "taobao.item.get"); params.put("app_key", APP_KEY); params.put("fields", "num_iid,title,price,pic_url,props_name"); params.put("num_iid", itemId); params.put("sign", generateSign(params)); String response = restTemplate.postForObject(apiUrl, params, String.class); return parseResponse(response); }}
三、1688商品采集实现(模拟请求)
1688开放平台门槛较高,对于小量采集可采用模拟浏览器请求的方式。
java
@Componentpublic class AlibabaProductCollector { public ProductInfo collect(String url) { // 设置代理IP池,防止被封 CloseableHttpClient httpClient = HttpClients.custom() .setProxy(new HttpHost(PROXY_HOST, PROXY_PORT)) .setDefaultRequestConfig(RequestConfig.custom() .setConnectionRequestTimeout(5000) .setSocketTimeout(10000) .build()) .build(); HttpGet httpGet = new HttpGet(url); httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"); httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { String html = EntityUtils.toString(response.getEntity(), "UTF-8"); Document doc = Jsoup.parse(html); ProductInfo product = new ProductInfo(); // 1688页面解析逻辑 product.setTitle(doc.select(".d-title h1").text()); product.setPrice(doc.select(".price").first().text()); // 解析SKU信息 Elements skuElements = doc.select(".sku-items li"); List skus = skuElements.stream().map(e -> { SKU sku = new SKU(); sku.setName(e.select(".sku-name").text()); sku.setValue(e.select(".sku-value").text()); return sku; }).collect(Collectors.toList()); product.setSkus(skus); return product; } }}
四、异步任务队列设计
采集操作耗时较长,必须异步处理,避免阻塞用户请求。Taoify跨境电商使用阿里云MNS消息队列。
java
@Servicepublic class CollectService { @Autowired private MnsClient mnsClient; public void submitCollectTask(String url, String platform, String userId) { CollectTask task = new CollectTask(url, platform, userId); // 发送到消息队列 mnsClient.sendMessage(QueueName.PRODUCT_COLLECT_QUEUE, JSON.toJSONString(task)); } @MnsListener(queueName = "PRODUCT_COLLECT_QUEUE") public void handleCollectTask(String message) { CollectTask task = JSON.parseObject(message, CollectTask.class); ProductInfo product = collect(task.getUrl(), task.getPlatform()); // 存入数据库,关联用户 productMapper.insert(product); // 发送WebSocket通知前端采集完成 webSocketService.sendNotification(task.getUserId(), product); }}
五、反爬策略与容灾
为防止IP被封,我们构建了代理IP池(使用阿里云弹性IP池动态切换)。同时配置了重试机制和死信队列,采集失败的任务会自动重试3次,仍失败则进入死信表人工处理。