1616| 参数名 | 数据类型 | 必填 | 默认值 | 说明 |
1717| :--- | :--- | :--- | :--- | :--- |
1818| ` query ` | string | 是 | - | 搜索关键词 |
19- | ` max_results ` | int | 否 | ` 10 ` | 返回的最大结果数量 |
19+ | ` max_results ` | int | 否 | ` 10 ` | 返回的最大结果数量(1-20) |
2020| ` search_type ` | string | 否 | ` text ` | 搜索类型:` text ` (文字搜索) 或 ` image ` (图片搜索) |
21+ | ` region ` | string | 否 | ` cn-zh ` | 搜索区域,如 ` cn-zh ` (中国)、` us-en ` (美国)、` uk-en ` (英国) 等 |
22+ | ` timeout ` | int | 否 | ` 15 ` | 请求超时时间(秒) |
23+ | ` proxy ` | string | 否 | ` None ` | 代理服务器地址,格式如 ` http://proxy.example.com:8080 ` |
2124
2225---
2326
@@ -28,7 +31,9 @@ from ddgs import DDGS
2831import json
2932
3033
31- def duckduckgo_search (query , max_results = 10 , search_type = ' text' ):
34+ def duckduckgo_search (
35+ query , max_results = 10 , search_type = " text" , region = " cn-zh" , timeout = 15 , proxy = None
36+ ):
3237 """
3338 使用 DuckDuckGo 进行搜索(统一入口函数)
3439
@@ -48,27 +53,40 @@ def duckduckgo_search(query, max_results=10, search_type='text'):
4853 if max_results > 20 :
4954 max_results = 20
5055 # 创建 DDGS 实例并执行搜索
51- with DDGS() as ddgs:
52- if search_type == ' image' :
53- results = list (ddgs.images(
54- keywords = query,
55- max_results = max_results
56- ))
57- else :
58- results = list (ddgs.text(
59- keywords = query,
60- max_results = max_results
61- ))
56+ ddgs = DDGS(timeout = timeout, proxy = proxy)
57+ if search_type == " image" :
58+ results = list (
59+ ddgs.images(
60+ query = query,
61+ region = region,
62+ max_results = max_results,
63+ )
64+ )
65+ else :
66+ results = list (
67+ ddgs.text(query = query, region = region, max_results = max_results)
68+ )
6269
6370 # 返回 JSON 格式的结果
6471 return json.dumps(results, ensure_ascii = False , indent = 2 )
6572
6673 except Exception as e:
6774 error_result = {
6875 " error" : str (e),
69- " message" : f " { search_type} 搜索失败,请检查网络连接或稍后重试 "
76+ " message" : f " { search_type} 搜索失败,请检查网络连接或稍后重试 " ,
7077 }
7178 return json.dumps(error_result, ensure_ascii = False , indent = 2 )
79+
80+
81+ if __name__ == " __main__" :
82+ query = " 猫"
83+ max_results = 5
84+ search_type = " image"
85+ region = " cn-zh"
86+ timeout = 15
87+ result = duckduckgo_search(query, max_results, search_type, region, timeout)
88+ print (result)
89+
7290```
7391
7492---
0 commit comments