Certainly! Below is a comprehensive Python script that accomplishes the following:
- Searches for Relevant URLs using the Bing Search API based on the query "cross-border trade".
- Filters URLs against a whitelist of trusted domains.
- Scrapes data from the filtered URLs to extract information about regulations, incentives, and grants.
- Stores the extracted data in a Neo4j knowledge graph, establishing relationships between different entities.
Prerequisites
Before running the script, ensure you have the following:
-
Bing Search API Key: You can obtain this from the Azure Cognitive Services.
-
Neo4j Database: Install Neo4j and ensure it's running. You can download it from the official website.
-
Python Packages: Install the required Python packages using pip:
pip install requests beautifulsoup4 neo4j
Python Script
import requests
from bs4 import BeautifulSoup
from neo4j import GraphDatabase
import re
import time
from urllib.parse import urlparse
# --------------------------- Configuration --------------------------- #
# Bing Search API Configuration
BING_API_KEY = 'YOUR_BING_API_KEY' # Replace with your Bing API key
BING_SEARCH_ENDPOINT = 'https://api.bing.microsoft.com/v7.0/search'
SEARCH_QUERY = 'cross-border trade'
SEARCH_COUNT = 50 # Number of search results to retrieve
# Whitelist of Trusted Domains
WHITELIST_DOMAINS = [
'gov',
'un.org',
'worldbank.org',
'europa.eu',
'trade.gov',
'wto.org',
'commerce.gov',
'federalregister.gov',
# Add more trusted domains as needed
]
# Neo4j Configuration
NEO4J_URI = "bolt://localhost:7687" # Default Neo4j URI
NEO4J_USER = "neo4j" # Your Neo4j username
NEO4J_PASSWORD = "your_password" # Your Neo4j password
# Scraping Configuration
HEADERS = {
'User-Agent': 'Mozilla/5.0 (compatible; WebCrawler/1.0; +http://yourdomain.com/crawler)'
}
REQUEST_TIMEOUT = 10 # Seconds
# --------------------------------------------------------------------- #
# Initialize Neo4j driver
driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
def search_bing(query, api_key, count=50):
"""
Searches Bing for the given query and returns a list of URLs.
"""
headers = {"Ocp-Apim-Subscription-Key": api_key}
params = {"q": query, "count": count}
response = requests.get(BING_SEARCH_ENDPOINT, headers=headers, params=params)
if response.status_code != 200:
print(f"Error fetching search results: {response.status_code}")
return []
search_results = response.json()
urls = []
if 'webPages' in search_results:
for page in search_results['webPages']['value']:
urls.append(page['url'])
else:
print("No web pages found in search results.")
return urls
def is_trusted(url, whitelist):
"""
Checks if the URL belongs to a trusted domain.
"""
try:
parsed_url = urlparse(url)
domain = parsed_url.netloc.lower()
for trusted in whitelist:
if trusted in domain:
return True
return False
except Exception as e:
print(f"Error parsing URL {url}: {e}")
return False
def scrape_page(url):
"""
Scrapes the content of the given URL and returns the text.
"""
try:
response = requests.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Remove scripts and styles
for script in soup(["script", "style"]):
script.decompose()
text = soup.get_text(separator=' ', strip=True)
return text
except requests.exceptions.RequestException as e:
print(f"Request error for {url}: {e}")
except Exception as e:
print(f"Error scraping {url}: {e}")
return None
def parse_content(text):
"""
Parses the scraped text to extract regulations, incentives, and grants.
This function uses simple regex patterns for demonstration and can be enhanced.
"""
regulations = re.findall(r'\bregulation[s]?\b[^.?!]*[.?!]', text, re.IGNORECASE)
incentives = re.findall(r'\bincentive[s]?\b[^.?!]*[.?!]', text, re.IGNORECASE)
grants = re.findall(r'\bgrant[s]?\b[^.?!]*[.?!]', text, re.IGNORECASE)
# Clean and deduplicate
regulations = list(set([reg.strip() for reg in regulations]))
incentives = list(set([inc.strip() for inc in incentives]))
grants = list(set([gr.strip() for gr in grants]))
return {
'regulations': regulations,
'incentives': incentives,
'grants': grants
}
def store_in_neo4j(data, url):
"""
Stores the extracted data into the Neo4j knowledge graph.
"""
with driver.session() as session:
# Create URL node
session.write_transaction(create_url_node, url)
# Create Regulation nodes and relationships
for reg in data['regulations']:
session.write_transaction(create_regulation_relationship, reg, url)
# Create Incentive nodes and relationships
for inc in data['incentives']:
session.write_transaction(create_incentive_relationship, inc, url)
# Create Grant nodes and relationships
for gr in data['grants']:
session.write_transaction(create_grant_relationship, gr, url)
def create_url_node(tx, url):
"""
Creates a URL node in Neo4j.
"""
tx.run("""
MERGE (u:URL {url: $url})
""", url=url)
def create_regulation_relationship(tx, regulation, url):
"""
Creates a Regulation node and relationship to the URL.
"""
tx.run("""
MERGE (r:Regulation {text: $regulation})
MERGE (u:URL {url: $url})
MERGE (u)-[:HAS_REGULATION]->(r)
""", regulation=regulation, url=url)
def create_incentive_relationship(tx, incentive, url):
"""
Creates an Incentive node and relationship to the URL.
"""
tx.run("""
MERGE (i:Incentive {text: $incentive})
MERGE (u:URL {url: $url})
MERGE (u)-[:HAS_INCENTIVE]->(i)
""", incentive=incentive, url=url)
def create_grant_relationship(tx, grant, url):
"""
Creates a Grant node and relationship to the URL.
"""
tx.run("""
MERGE (g:Grant {text: $grant})
MERGE (u:URL {url: $url})
MERGE (u)-[:HAS_GRANT]->(g)
""", grant=grant, url=url)
def main():
print("Starting web crawler...")
# Step 1: Search for Relevant URLs
print(f"Searching Bing for query: '{SEARCH_QUERY}'")
urls = search_bing(SEARCH_QUERY, BING_API_KEY, SEARCH_COUNT)
print(f"Total URLs found: {len(urls)}")
# Step 2: Filter for Trusted Sources
trusted_urls = [url for url in urls if is_trusted(url, WHITELIST_DOMAINS)]
print(f"Trusted URLs after filtering: {len(trusted_urls)}")
# Step 3: Scrape and Process Each Trusted URL
for idx, url in enumerate(trusted_urls, start=1):
print(f"\n[{idx}/{len(trusted_urls)}] Scraping URL: {url}")
content = scrape_page(url)
if content:
print("Parsing content...")
parsed_data = parse_content(content)
print(f" - Regulations found: {len(parsed_data['regulations'])}")
print(f" - Incentives found: {len(parsed_data['incentives'])}")
print(f" - Grants found: {len(parsed_data['grants'])}")
# Step 4: Store Data in Neo4j
print("Storing data in Neo4j...")
store_in_neo4j(parsed_data, url)
print("Data stored successfully.")
else:
print("No content scraped; skipping.")
# Polite crawling: wait between requests
time.sleep(1) # Adjust as needed
print("\nWeb crawling completed.")
# --------------------------- Neo4j Cleanup --------------------------- #
def close_connection():
"""
Closes the Neo4j driver connection.
"""
driver.close()
# --------------------------------------------------------------------- #
if __name__ == "__main__":
try:
main()
finally:
close_connection()
Explanation of the Script
-
Configuration Section:
- Bing Search API: Set your Bing API key, search endpoint, query, and the number of results you want.
- Whitelist Domains: Define a list of trusted domains to filter URLs. Ensure that only URLs from these domains are processed.
- Neo4j Configuration: Provide the URI, username, and password for your Neo4j instance.
- Scraping Configuration: Define headers to mimic a browser request and set a reasonable timeout for HTTP requests.
-
Functions:
search_bing(): Queries the Bing Search API and retrieves a list of URLs based on the search query.
is_trusted(): Checks if a URL belongs to a trusted domain using urlparse for accurate domain extraction.
scrape_page(): Fetches the content of a URL and extracts visible text using BeautifulSoup, excluding scripts and styles.
parse_content(): Uses regular expressions to find sentences containing keywords like "regulation", "incentive", and "grant". This can be enhanced with more sophisticated NLP techniques as needed.
store_in_neo4j(): Stores the extracted data into Neo4j, creating nodes and relationships for URLs, regulations, incentives, and grants.
- Helper functions like
create_url_node, create_regulation_relationship, etc., are used to interact with Neo4j in a transactional manner.
-
Main Function:
- Step 1: Searches Bing for the specified query and retrieves URLs.
- Step 2: Filters these URLs against the whitelist to ensure only trusted sources are processed.
- Step 3: Iterates over each trusted URL, scrapes its content, parses the relevant information, and stores it in Neo4j.
- Politeness: Adds a delay between requests to avoid overwhelming servers (adjustable as needed).
-
Neo4j Cleanup:
- Ensures that the Neo4j driver connection is properly closed after the script completes execution.
Enhancements and Considerations
- Error Handling: The script includes basic error handling, but you may want to enhance it based on specific requirements.
- Advanced Parsing: For more accurate data extraction, consider integrating natural language processing (NLP) techniques or using structured data like JSON-LD if available on the scraped pages.
- Respect Robots.txt: To adhere to ethical scraping practices, consider checking the
robots.txt file of each domain to ensure you're allowed to scrape the content.
- Scalability: For large-scale crawling, consider using frameworks like Scrapy and implementing asynchronous processing.
- Rate Limiting: Be mindful of the rate limits imposed by both the Bing Search API and the target websites to avoid being blocked.
Running the Script
-
Set Up Neo4j: Ensure that Neo4j is running and accessible at the specified URI with the correct credentials.
-
Insert Your Bing API Key: Replace 'YOUR_BING_API_KEY' with your actual Bing Search API key.
-
Execute the Script:
python web_crawler.py
Replace web_crawler.py with the filename you've saved the script as.
-
Verify in Neo4j: After execution, you can open the Neo4j Browser (usually at http://localhost:7474) to visualize and query the knowledge graph.
Sample Cypher Queries in Neo4j
-
Find All Regulations Related to a Specific URL:
MATCH (u:URL {url: "https://example.com"})-[:HAS_REGULATION]->(r:Regulation)
RETURN r.text
-
Find All URLs That Mention a Specific Regulation:
MATCH (u:URL)-[:HAS_REGULATION]->(r:Regulation {text: "Specific Regulation Text"})
RETURN u.url
-
Explore Relationships Between Incentives and Grants:
(Assuming additional relationships are defined)
MATCH (i:Incentive)-[:RELATED_TO]->(g:Grant)
RETURN i.text, g.text
This script provides a foundational framework for building a topic-based web crawler that integrates with a Neo4j knowledge graph. Depending on your specific use case, you can further tailor the scraping logic, data extraction methods, and graph schema to better fit your requirements.