Skip to main content
Open In ColabOpen on GitHub

DataForSEO

DataForSeo provides comprehensive SEO and digital marketing data solutions via API.

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")

自定义位置和语言

您可以通过向 API 包装器传递额外的参数来指定搜索结果的位置和语言。

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")

自定义搜索类型

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 参考:工具