Introduction
In this tutorial, you'll learn how to create and deploy an AI agent using OpenAI's API that can systematically scrape and analyze web data. This hands-on guide will demonstrate how to build a web scraping agent that can interact with web APIs and HTML content, similar to the UN website scanning incident mentioned in the news article. You'll gain practical experience with OpenAI's function calling capabilities, web scraping techniques, and automated data collection methods.
Prerequisites
- Python 3.8 or higher installed on your system
- OpenAI API key (available from openai.com)
- Basic understanding of Python programming and REST APIs
- Install required Python packages:
openai,requests,beautifulsoup4,lxml
Step-by-Step Instructions
Step 1: Set Up Your Development Environment
First, create a new Python project directory and install the required dependencies:
mkdir ai-web-scraper
cd ai-web-scraper
pip install openai requests beautifulsoup4 lxml
Why: This creates a clean project space and installs the necessary libraries for web scraping and AI interaction.
Step 2: Initialize OpenAI Client
Create a new Python file called scraper.py and set up your OpenAI client:
import openai
import os
# Set your API key
openai.api_key = os.getenv('OPENAI_API_KEY')
# Initialize client
client = openai.OpenAI()
Why: This establishes the connection to OpenAI's API service that will power your agent's intelligence.
Step 3: Create a Web Scraping Function
Implement a basic web scraping function that can fetch and parse HTML content:
import requests
from bs4 import BeautifulSoup
def fetch_webpage(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
return soup
except requests.RequestException as e:
print(f"Error fetching {url}: {e}")
return None
Why: This function handles the actual HTTP requests and HTML parsing, which is fundamental for any web scraping agent.
Step 4: Define AI Agent Functions
Define the functions that your AI agent will be able to call:
def analyze_webpage_content(soup):
"""Analyze webpage content and extract key information"""
if not soup:
return "No content to analyze"
title = soup.title.string if soup.title else "No title"
paragraphs = soup.find_all('p')
# Extract first few paragraphs
summary = ' '.join([p.get_text()[:100] for p in paragraphs[:3] if p.get_text()])
return {
'title': title,
'summary': summary,
'paragraph_count': len(paragraphs)
}
def extract_statistics_data(soup):
"""Extract statistical data from the webpage"""
if not soup:
return "No content to analyze"
# Look for table data
tables = soup.find_all('table')
stats_data = []
for table in tables:
rows = table.find_all('tr')
table_data = []
for row in rows:
cells = row.find_all(['td', 'th'])
row_data = [cell.get_text().strip() for cell in cells]
if row_data:
table_data.append(row_data)
stats_data.append(table_data)
return stats_data
Why: These functions represent the capabilities your AI agent will have when interacting with web content, mimicking the data extraction behavior seen in the UN website incident.
Step 5: Configure OpenAI Function Calling
Set up the function definitions that your AI agent will use:
functions = [
{
"name": "fetch_webpage",
"description": "Fetch and parse webpage content",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The URL to fetch"
}
},
"required": ["url"]
}
},
{
"name": "analyze_webpage_content",
"description": "Analyze webpage content and extract key information",
"parameters": {
"type": "object",
"properties": {
"soup": {
"type": "object",
"description": "BeautifulSoup object of webpage content"
}
},
"required": ["soup"]
}
},
{
"name": "extract_statistics_data",
"description": "Extract statistical data from webpage tables",
"parameters": {
"type": "object",
"properties": {
"soup": {
"type": "object",
"description": "BeautifulSoup object of webpage content"
}
},
"required": ["soup"]
}
}
]
Why: This configuration tells OpenAI's API which functions your agent can call, enabling it to make decisions about what actions to take during web interactions.
Step 6: Create the Main AI Agent Loop
Implement the core logic that will orchestrate your AI agent's activities:
def run_ai_web_agent(urls):
"""Main function to run the AI web scraping agent"""
for url in urls:
print(f"\nAnalyzing: {url}")
# Fetch webpage
soup = fetch_webpage(url)
if not soup:
continue
# Ask AI to analyze content
response = client.chat.completions.create(
model="gpt-4",
messages=[
{
"role": "system",
"content": "You are a web content analyzer. You can fetch webpages and extract information from them."
},
{
"role": "user",
"content": f"Analyze this webpage: {url}"
}
],
functions=functions,
function_call="auto"
)
# Process AI response
ai_message = response.choices[0].message
if ai_message.function_call:
function_name = ai_message.function_call.name
function_args = ai_message.function_call.arguments
print(f"AI called function: {function_name}")
# Execute the function call
if function_name == "analyze_webpage_content":
result = analyze_webpage_content(soup)
print(f"Analysis result: {result}")
elif function_name == "extract_statistics_data":
result = extract_statistics_data(soup)
print(f"Statistics extracted: {len(result)} tables found")
# Example usage
if __name__ == "__main__":
test_urls = [
"https://unctad.org",
"https://unctad.org/statistics"
]
run_ai_web_agent(test_urls)
Why: This creates the main execution loop that demonstrates how an AI agent would systematically process multiple webpages, similar to the UN website scanning behavior.
Step 7: Add Rate Limiting and Logging
Implement rate limiting to prevent overwhelming servers and add logging:
import time
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Rate limiting
def rate_limited_request(url, delay=1):
try:
time.sleep(delay) # Rate limiting
response = requests.get(url, timeout=10)
response.raise_for_status()
logger.info(f"Successfully fetched {url}")
return BeautifulSoup(response.content, 'html.parser')
except requests.RequestException as e:
logger.error(f"Error fetching {url}: {e}")
return None
Why: Rate limiting is crucial for responsible web scraping and prevents your agent from being blocked or causing server issues, which is a key concern in the security context of the original incident.
Step 8: Test Your AI Agent
Run your agent with a test URL to see it in action:
if __name__ == "__main__":
test_urls = [
"https://httpbin.org/delay/1",
"https://httpbin.org/html"
]
run_ai_web_agent(test_urls)
Why: Testing with known endpoints helps verify that your agent functions correctly before deploying it against real websites.
Summary
This tutorial demonstrated how to build an AI-powered web scraping agent using OpenAI's API capabilities. You've learned how to set up an AI agent that can fetch webpages, analyze content, and extract statistical data. The agent mimics the systematic scanning behavior observed in the UN website incident, but with proper rate limiting and logging. This implementation showcases how AI agents can be designed to automatically interact with web content, highlighting both the capabilities and security considerations mentioned in the news article.
Remember that while this technology is powerful, it should be used responsibly and ethically. Always respect website terms of service, implement appropriate rate limiting, and consider the privacy implications of automated web scraping.