Skip to main content
Open In ColabOpen on GitHub

DataForSEO

DataForSeo 通过 API 提供全面的 SEO 和数字营销数据解决方案。

The DataForSeo API retrieves SERP from the most popular search engines like Google, Bing, Yahoo. It also allows to >get SERPs from different search engine types like Maps, News, Events, etc.

这本笔记本演示了如何使用DataForSeo API来获取搜索引擎结果。

%pip install --upgrade --quiet langchain-community
from langchain_community.utilities.dataforseo_api_search import DataForSeoAPIWrapper

设置 API 凭证

您可以注册在DataForSeo网站以获得API凭证。

import os

os.environ["DATAFORSEO_LOGIN"] = "your_api_access_username"
os.environ["DATAFORSEO_PASSWORD"] = "your_api_access_password"

wrapper = DataForSeoAPIWrapper()

run 方法将返回以下元素之一的第一个结果片段:answer_box、knowledge_graph、featured_snippet、shopping、organic。

wrapper.run("Weather in Los Angeles")

runresults 之间的区别

runresults 是由 DataForSeoAPIWrapper 类提供的两种方法。

run 方法执行搜索,并从答案框、知识图谱、精选摘要、购物或自然结果中返回第一个结果片段。这些元素按优先级从高到低排序。

results 方法会根据包装器中设置的参数返回一个 JSON 响应。这使得从 API 返回的数据内容具有更高的灵活性。

获取结果作为JSON

您可以自定义希望在JSON响应中返回的结果类型和字段。您还可以设置要返回的顶级结果的最大数量。

json_wrapper = DataForSeoAPIWrapper(
json_result_types=["organic", "knowledge_graph", "answer_box"],
json_result_fields=["type", "title", "description", "text"],
top_count=3,
)
json_wrapper.results("Bill Gates")

自定义位置和语言

您可以使用附加参数指定搜索结果的位置和语言。

customized_wrapper = DataForSeoAPIWrapper(
top_count=10,
json_result_types=["organic", "local_pack"],
json_result_fields=["title", "description", "type"],
params={"location_name": "Germany", "language_code": "en"},
)
customized_wrapper.results("coffee near me")

自定义搜索引擎

您可以指定想要使用的搜索引擎。

customized_wrapper = DataForSeoAPIWrapper(
top_count=10,
json_result_types=["organic", "local_pack"],
json_result_fields=["title", "description", "type"],
params={"location_name": "Germany", "language_code": "en", "se_name": "bing"},
)
customized_wrapper.results("coffee near me")

自定义搜索类型

The API封装器还允许您指定要执行的搜索类型。例如,您可以执行地图搜索。

maps_search = DataForSeoAPIWrapper(
top_count=10,
json_result_fields=["title", "value", "address", "rating", "type"],
params={
"location_coordinate": "52.512,13.36,12z",
"language_code": "en",
"se_type": "maps",
},
)
maps_search.results("coffee near me")

集成与LangChain智能代理

您可以使用来自langchain.agents模块的Tool类将DataForSeoAPIWrapper与langchain代理集成。Tool类封装了一个代理可以调用的功能。

from langchain_core.tools import Tool

search = DataForSeoAPIWrapper(
top_count=3,
json_result_types=["organic"],
json_result_fields=["title", "description", "type"],
)
tool = Tool(
name="google-search-answer",
description="My new answer tool",
func=search.run,
)
json_tool = Tool(
name="google-search-json",
description="My new json tool",
func=search.results,
)
API 参考:工具