使用无头浏览器时,您可以定义在渲染JavaScript时执行的自定义浏览器指令。
如何使用?
要使用浏览器指令,请在创建作业时提供一组browser_instructions
。
比如说,您想在网站上搜索pizza boxes
这个词。
示例作业参数如下:
{
"source": "universal",
"url": "https://www.ebay.com/",
"render": "html",
"browser_instructions": [
{
"type": "input",
"value": "pizza boxes",
"selector": {
"type": "xpath",
"value": "//input[@class='gh-tb ui-autocomplete-input']"
}
},
{
"type": "click",
"selector": {
"type": "xpath",
"value": "//input[@type='submit']"
}
},
{
"type": "wait",
"wait_time_s": 5
}
]
}
第一步:您必须提供"render": "html"
参数。
第二步:浏览器指令应该在"browser_instructions"
字段。
上述示例浏览器指令指定的目标是在搜索字段中输入搜索词pizza boxes,点击搜索按钮,并等待5秒钟以加载内容。
抓取的结果应如下所示:
{
"results": [
{
"content": "<!doctype html><html>
Content after executing the instructions
</html>",
"created_at": "2023-10-11 11:35:23",
"updated_at": "2023-10-11 11:36:08",
"page": 1,
"url": "https://www.ebay.com/",
"job_id": "7117835067442906113",
"status_code": 200
}
]
}
抓取的HTML应该如下所示:
获取浏览器资源
我们提供了一个独立的浏览器指令来获取浏览器资源。该功能在此处定义。
使用fetch_resource
将导致作业返回与提供的格式匹配的第一个Fetch/XHR资源,而不是目标HTML。
比方说,我们想要定位在浏览器中自然访问产品页面时获取的GraphQL资源。我们将提供作业信息如下:
{
"source": "universal",
"url": "https://www.example.com/product-page/123",
"render": "html",
"browser_instructions": [
{
"type": "fetch_resource",
"format": "/graphql/product-info/123"
}
]
}
这些指令将导致如下结果:
{
"results": [
{
"content": "{'product_id': 123, 'description': '', 'price': 123}",
"created_at": "2023-10-11 11:35:23",
"updated_at": "2023-10-11 11:36:08",
"page": 1,
"url": "https://example.com/v1/graphql/product-info/123/",
"job_id": "7117835067442906114",
"status_code": 200
}
]
}
支持的浏览器指令列表
状态码
请参阅此处概述的响应代码。
有关指令验证的状态码在此处记录。
错误和警告
如果由于您的浏览操作而导致错误或警告,您将在结果中找到它,其键为browser_instructions_error
或browser_instructions_warnings
。例如,如果您发送了以下浏览器指令,而页面上没有找到预期的xpath,则结果将包含一个警告。
browser_instructions
:
[
{
"type": "input",
"selector": {
"type": "xpath",
"value": "//input[@type='search']"
},
"value": "oxylabs"
}
]
结果:
{
"results": [
{
"content": "<!doctype html><html>
Content after executing the instructions
</html>",
"created_at": "2023-10-11 11:35:23",
"updated_at": "2023-10-11 11:36:08",
"browser_instructions_warnings": [
{
"action_type": "click",
"msg": "Unable to find selector type `xpath` with value `//input[@type=search]` on the page."
},
],
"page": 1,
"url": "https://example.com",
"job_id": "7117835067442906113",
"status_code": 200
}
]
}
在执行{action.type}
浏览器指令时发生意外错误。
在页面上找不到选择器类型{selector.type}
,值为{selector.value}
。