Nova Act SDKはPythonで記述されているため、既存のPythonプロジェクトに簡単に組み込むことができます。操作の間にテストコードやエラー処理、データ加工ロジックを挿入したり、スレッドプールで並列処理を実装したりと、開発者が業務要件に応じた柔軟な制御が可能です。
from nova_act import NovaAct
import pandas as pd
from concurrent.futures import ThreadPoolExecutor
# 複数のショッピングサイトで価格比較を行う例
sites = ["amazon.com", "walmart.com", "target.com"]
product = "coffee maker"
results = []
def check_price(site):
with NovaAct(starting_page=f"https://www.{site}") as n:
n.act(f"search for {product}")
n.act("click on the first result")
price = n.extract("find the price of the product")
return {"site": site, "price": price}
# 並列実行
with ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(check_price, sites))
# 結果を表示
df = pd.DataFrame(results)
print(df.sort_values("price"))
from nova_act import NovaAct
# オンラインショップで特定製品の価格をチェックする例
with NovaAct(starting_page="https://www.bestbuy.com") as n:
# サイトでゲーミングノートPCを検索
n.act("search for gaming laptop with RTX 4070")
# フィルターを適用して結果を絞り込む
n.act("filter by price range between $1000 and $1500")
n.act("sort by customer rating from highest to lowest")
# 最初の3つの結果の情報を取得
n.act("get the name, price, and rating of the first three laptops")
# 気に入った商品を見つけたら詳細ページへ
n.act("click on the second laptop in the results")
# 仕様の確認
n.act("scroll down to specifications section")
n.act("check if it has at least 16GB RAM and 1TB storage")
# 在庫確認と配送オプションの確認
n.act("check if the item is in stock for delivery")
from nova_act import NovaAct
n = NovaAct(starting_page="https://www.amazon.com")
n.start() # ブラウザを起動
# 操作を1つずつ実行
n.act("search for a coffee maker")
# ブラウザ上で動作確認後、次の操作
n.act("select the first result")
この方法で、各ステップの動作を確認しながら開発を進められます!
データ抽出の例
Nova Act SDKでは、Webページから構造化データを簡単に抽出できます。
from nova_act import NovaAct
from pydantic import BaseModel
from typing import Optional, List
# データモデルを定義
class Product(BaseModel):
name: str
price: float
rating: Optional[float] = None
reviews: Optional[int] = None
with NovaAct(starting_page="https://www.amazon.com") as n:
n.act("search for coffee makers")
# 複数の商品情報を抽出
products = n.extract(Product, multiple=True)
# 結果を表示
for product in products:
print(f"商品名: {product.name}")
print(f"価格: ${product.price}")
if product.rating:
print(f"評価: {product.rating}⭐ ({product.reviews}件のレビュー)")
print("---")
class Apartment(BaseModel):
address: str
price: float
bedrooms: int
bathrooms: float
sqft: Optional[int] = None
# 物件情報を抽出
with NovaAct(starting_page="https://www.realestate.com") as n:
n.act("search for 2 bedroom apartments in Redwood City")
apartments = n.extract(Apartment, multiple=True)
# 各物件の最寄り駅までの距離を調査
def add_station_distance(apartment):
with NovaAct(starting_page="https://maps.google.com") as n:
n.act(f"get directions from {apartment.address} to nearest train station by bike")
distance = n.extract("find the biking distance in minutes")
apartment.station_distance = distance
return apartment
# 並列処理で効率的に情報収集
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=5) as executor:
apts_with_distance = list(executor.map(add_station_distance, apartments))
# 駅からの距離でソート
import pandas as pd
df = pd.DataFrame(apts_with_distance)
df.sort_values("station_distance")
②定期注文の自動実行
特定の曜日や時間に自動で注文するエージェントも簡単に構築できます!
import schedule
import time
def order_salad():
with NovaAct(user_data_dir="./my_chrome_profile") as n: # ログイン済みのブラウザプロファイル
n.act("go to sweetgreen.com")
n.act("select my usual salad")
n.act("proceed to checkout")
n.act("select delivery for tonight")
n.act("complete the order")
print("夕食のサラダを注文しました!")
# 毎週火曜日の18時に実行
schedule.every().tuesday.at("18:00").do(order_salad)
while True:
schedule.run_pending()
time.sleep(60)
③旅行予約の自動化
旅行の計画と予約を自動化するエージェントを構築する例です。
from nova_act import NovaAct
from datetime import datetime, timedelta
from pydantic import BaseModel
from typing import List, Optional
class FlightOption(BaseModel):
airline: str
departure_time: str
arrival_time: str
duration: str
stops: int
price: float
# 旅行日程を設定
departure_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
return_date = (datetime.now() + timedelta(days=37)).strftime("%Y-%m-%d")
# フライト検索
with NovaAct(starting_page="https://www.expedia.com") as n:
n.act("go to flights section")
n.act("select round trip")
n.act("set departure from New York")
n.act("set destination to Tokyo")
n.act(f"set departure date to {departure_date}")
n.act(f"set return date to {return_date}")
n.act("search for flights")
# フィルターを適用
n.act("filter for flights with 1 stop or less")
n.act("sort by price from lowest to highest")
# 上位5件のフライト情報を抽出
flights = n.extract(FlightOption, multiple=True, limit=5)
# 最安値のフライトを選択
n.act("select the cheapest flight option")
# ホテルも検索
n.act("add hotel to this trip")
n.act("search for hotels in Tokyo city center")
n.act("filter for 4-star hotels or better")
n.act("select the hotel with the best reviews in the first 5 results")
# レンタカーはスキップ
n.act("skip rental car")
# 予約情報の確認
booking_summary = n.extract("get the total price and booking details")
print(f"予約内容: {booking_summary}")
④ソーシャルメディア管理の自動化
複数のソーシャルメディアプラットフォームでの投稿管理を自動化する例です。
from nova_act import NovaAct
import csv
from datetime import datetime
# 投稿予定コンテンツをCSVから読み込む
posts = []
with open('social_media_schedule.csv', 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
posts.append(row)
# 今日の日付に対応する投稿を探す
today = datetime.now().strftime("%Y-%m-%d")
todays_posts = [post for post in posts if post['scheduled_date'] == today]
# 各プラットフォームに投稿
for post in todays_posts:
platform = post['platform']
content = post['content']
image_path = post.get('image_path', None)
if platform == 'twitter':
with NovaAct(user_data_dir="./twitter_profile") as n:
n.act("go to twitter.com")
n.act("click on 'Post' button")
n.act(f"type '{content}'")
if image_path:
# Playwrightを使って画像をアップロード
n.page.locator("input[type='file']").set_input_files(image_path)
n.act("click 'Post' to publish")
elif platform == 'linkedin':
with NovaAct(user_data_dir="./linkedin_profile") as n:
n.act("go to linkedin.com")
n.act("click on 'Start a post' button")
n.act(f"type '{content}'")
if image_path:
n.act("click on 'Add image' button")
# Playwrightを使って画像をアップロード
n.page.locator("input[type='file']").set_input_files(image_path)
n.act("click 'Post' to publish")
elif platform == 'instagram':
with NovaAct(user_data_dir="./instagram_profile") as n:
n.act("go to instagram.com")
n.act("click on 'Create' button")
if image_path:
# Playwrightを使って画像をアップロード
n.page.locator("input[type='file']").set_input_files(image_path)
n.act("click 'Next'")
n.act(f"type '{content}' in the caption field")
n.act("click 'Share' to publish")
print(f"{platform}に投稿完了: {content[:30]}...")
ぜひ参考にしてください!
Nova Actの料金
Nova Act SDKは、Apache-2.0ライセンスでGitHubに公開されており、無料で利用できます。