提取规则
跳过 BeautifulSoup、Cheerio 和正则表达式。告诉 Shifter 哪些 CSS 选择器对应哪些 JSON 字段,即可获得干净的 JSON 数据。
将 extract_rules 作为经过 URL 编码的 JSON 对象传递,其中每个键是一个输出字段,每个值描述如何提取该字段。
最简示例:
{ "title": { "selector": "h1", "output": "text" }}经过 URL 编码后发送:
curl "https://scrape.shifter.io/v1?api_key=YOUR_API_KEY&url=https://example.com&extract_rules=%7B%22title%22%3A%7B%22selector%22%3A%22h1%22%2C%22output%22%3A%22text%22%7D%7D"
# {"title": "Example Domain"}output | 返回内容 | 示例 |
|---|---|---|
text | 元素的文本内容 | "Example Domain" |
html | 内部 HTML | "<strong>Example</strong> Domain" |
@<attr> | 属性值 | "@href" → "https://example.com/" |
在规则对象中添加更多键即可:
{ "title": { "selector": "h1", "output": "text" }, "description": { "selector": "meta[name=description]", "output": "@content" }, "canonical": { "selector": "link[rel=canonical]", "output": "@href" }}响应:
{ "title": "Example Domain", "description": "The example domain...", "canonical": "https://example.com/"}对于列表类内容(搜索结果、产品卡片、表格行),将规则包裹在一个指定了 type: "list" 和 item 的父级中:
{ "products": { "selector": "div.product", "type": "list", "item": { "name": { "selector": "h2", "output": "text" }, "price": { "selector": ".price", "output": "text" }, "link": { "selector": "a.title", "output": "@href" } } }}响应:
{ "products": [ { "name": "Item A", "price": "$19.99", "link": "/item-a" }, { "name": "Item B", "price": "$24.50", "link": "/item-b" } ]}JSON 自动解析器
Section titled “JSON 自动解析器”对于已经返回 JSON 的端点(大多数 REST API),添加 auto_parser=1 即可解析响应体并原样返回:
curl "https://scrape.shifter.io/v1?api_key=YOUR_API_KEY&url=https://api.example.com/products&auto_parser=1"- 先在浏览器开发者控制台中测试选择器:
document.querySelector(...)。 - 正确转义经过 URL 编码的 JSON。当你将规则作为参数对象传递时,大多数 HTTP 客户端会自动完成此操作。
- 如果页面上缺少某个字段,该字段将返回
null,而不会导致请求失败。