# Variable

### 脚本示例

变量可以设置在脚本的任意参数中（除"method", "next", "if", "check", "condition", "loop"关键词)

```json
step = [{
    "method": "redirect",
    "url": "https://www.baidu.com/",
}, {
    "method": "input",
    "xpath": "//*[@id=\"kw\"]",
    "text": "__v-searchKey__",
    "if": {
        "condition": "presence",
        "xpath": "__v-button_xpath__"
    }
}, {
    "method": "clear"
}]
```

在编写脚本变量时，需要使用标识符"\_\_v-{your variable}\_\_"。否则在语法检查时会被判断为普通参数处理。

### 实现你自己的variable对象

你需要继承VariableBase对象，并且实现get、\_\_contains\_\_ 这两个方法

```python
import crawlipt as cpt
class Variable(cpt.VariableBase):
    @cpt.check
    def __init__(self, values: dict | str):
        if isinstance(values, str):
            values: dict = json.load(values)
        self.values = values

    @cpt.check
    def get(self, key: str) -> Any:
        return self.values.get(key)

    @cpt.check
    def __contains__(self, key: str):
        return key in self.values
```

上述实现已在crawlipt中内置

### 内置variable对象

脚本中的变量会在执行期间被自动替换，你可以创建crawlipt内置的Variable对象，初始化参数为字典或者json格式字符串。字典中需要将你的变量名以及值一一对应，在执行期间会替换脚本中的变量名为你设置的变量值。

```python
import crawlipt as cpt
v = cpt.Variable({
            "searchKey": "hello",
            "button_xpath": "//*[@id=\"su\"]"
        })
loader = cpt.Script(step, interval=3)
loader.process(webdriver=webdriver,
               variable=v) # 在执行阶段传入变量对象
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wwydev.gitbook.io/crawlipt-zh/zhi-nan/variable.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
