make a python game that navigates a web, extract the text from the main page and after it goes to another web page that there is a link there of the same domain and extracts the text, and so on. It does not extract if it is repeated, it navigates randomy until some specific time has passed and ends the program
Assistant
Sure! Below is a Python script that functions as a simple web navigator game. The script starts from a specified main URL, extracts the text from the page, finds all links within the same domain, and randomly navigates to one of these links. It avoids revisiting pages and continues this process until a specified amount of time has passed.
Overview
Starting Point: The script begins with a main URL provided by the user.
Text Extraction: It extracts and displays the textual content of the current page.
Link Extraction: It gathers all hyperlinks (<a> tags) that belong to the same domain.
Random Navigation: From the collected links, it randomly selects one that hasn't been visited yet.
Avoiding Repeats: It keeps track of visited URLs to avoid revisiting them.
Termination: The script runs for a user-defined duration and then gracefully exits.
Prerequisites
Before running the script, ensure you have the following Python packages installed:
requests: To make HTTP requests.
beautifulsoup4: To parse HTML content.
tldextract: To extract domain information.
colorama (optional): To add colored output for better readability.
import requests
from bs4 import BeautifulSoup
import tldextract
import time
import random
import sys
from urllib.parse import urljoin, urlparse
from colorama import Fore, Style, init
# Initialize colorama
init(autoreset=True)
class WebNavigatorGame:
def __init__(self, start_url, duration_seconds=60):
self.start_url = self.normalize_url(start_url)
self.domain = self.get_domain(self.start_url)
self.duration = duration_seconds
self.visited = set()
self.to_visit = []
self.texts = []
def normalize_url(self, url):
"""Ensure the URL has a scheme."""
parsed = urlparse(url)
if not parsed.scheme:
return "http://" + url
return url
def get_domain(self, url):
"""Extract the domain using tldextract."""
extracted = tldextract.extract(url)
domain = f"{extracted.domain}.{extracted.suffix}"
return domain.lower()
def get_page(self, url):
"""Fetch the content of a web page."""
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.text
except (requests.RequestException, requests.HTTPError) as e:
print(Fore.RED + f"Failed to retrieve {url}: {e}")
return None
def extract_text(self, html_content):
"""Extract text from HTML content."""
soup = BeautifulSoup(html_content, 'html.parser')
# Remove script and style elements
for script_or_style in soup(['script', 'style']):
script_or_style.decompose()
text = soup.get_text(separator=' ', strip=True)
return text
def extract_links(self, html_content, base_url):
"""Extract all unique, same-domain links from HTML content."""
soup = BeautifulSoup(html_content, 'html.parser')
links = set()
for link in soup.find_all('a', href=True):
href = link['href']
# Resolve relative URLs
full_url = urljoin(base_url, href)
normalized_url = self.normalize_url(full_url)
if self.get_domain(normalized_url) == self.domain:
# Remove fragment identifiers and query parameters for consistency
parsed = urlparse(normalized_url)
clean_url = parsed.scheme + "://" + parsed.netloc + parsed.path
links.add(clean_url)
return links
def run(self):
"""Run the web navigation game."""
start_time = time.time()
current_url = self.start_url
self.to_visit.append(current_url)
while time.time() - start_time < self.duration and self.to_visit:
current_url = self.to_visit.pop(0)
if current_url in self.visited:
continue
print(Fore.CYAN + f"\nVisiting: {current_url}")
self.visited.add(current_url)
html_content = self.get_page(current_url)
if html_content is None:
continue
text = self.extract_text(html_content)
self.texts.append(text)
print(Fore.GREEN + f"Extracted Text (first 200 chars):\n{text[:200]}...\n")
links = self.extract_links(html_content, current_url)
new_links = links - self.visited
if new_links:
self.to_visit.extend(list(new_links))
random.shuffle(self.to_visit) # Shuffle to ensure random navigation
else:
print(Fore.YELLOW + "No new links found on this page.")
print(Fore.MAGENTA + f"\nGame Over! Visited {len(self.visited)} pages.")
# Optionally, you can save or process the extracted texts further.
# For example, saving to a file:
# self.save_texts()
def save_texts(self, filename="extracted_texts.txt"):
"""Save all extracted texts to a file."""
with open(filename, 'w', encoding='utf-8') as f:
for idx, text in enumerate(self.texts, 1):
f.write(f"--- Page {idx} ---\n")
f.write(text + "\n\n")
print(Fore.BLUE + f"All texts have been saved to {filename}.")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python web_navigator_game.py <start_url> <duration_seconds>")
print("Example: python web_navigator_game.py https://example.com 120")
sys.exit(1)
start_url = sys.argv[1]
try:
duration = int(sys.argv[2])
except ValueError:
print("Duration must be an integer representing seconds.")
sys.exit(1)
game = WebNavigatorGame(start_url, duration)
game.run()
How to Use the Script
Save the Script: Save the script to a file named web_navigator_game.py.
Run the Script: Open your terminal or command prompt and navigate to the directory containing the script.
Execute with Arguments: The script requires two arguments:
Start URL: The initial website to start navigating from.
Duration (seconds): How long (in seconds) you want the game to run.
This command starts the game at https://example.com and runs it for 120 seconds (2 minutes).
Script Behavior Details
Normalization: The script ensures that the URLs have the correct scheme (http or https) to avoid request issues.
Domain Matching: It uses the tldextract library to extract the domain and ensures that only links within the same domain are followed.
Random Navigation: After extracting all eligible links from a page, it shuffles the list to ensure random navigation.
Avoiding Repeats: A set named visited keeps track of all URLs that have been visited to prevent revisiting the same page.
Text Extraction: The script extracts and prints the first 200 characters of the text from each visited page. You can modify this behavior as needed.
Error Handling: It gracefully handles HTTP errors and request exceptions, allowing the game to continue even if some pages fail to load.
Termination: The game stops after the specified duration and summarizes the number of pages visited.
Optional Enhancements
Saving Extracted Texts: The script includes a method save_texts which can be uncommented and called to save all extracted texts to a file.
Graphical Interface: For a more game-like experience, consider integrating a graphical user interface (GUI) using libraries like Tkinter or PyQt.
Interactive Navigation: Modify the script to allow user input for navigation choices instead of random selection, turning it into an interactive game.
Ethical Considerations
Respect robots.txt: Before crawling any website, ensure you respect its robots.txt rules to avoid accessing disallowed pages.
Rate Limiting: Implement delays between requests to avoid overwhelming the target server.
Legal Compliance: Ensure that your crawling activities comply with the website's terms of service and applicable laws.
Conclusion
This script provides a foundational approach to navigating and extracting information from websites in a controlled, random manner. You can expand upon it by adding features like depth limits, better text processing, data storage solutions, or more sophisticated navigation strategies. Always remember to use such tools responsibly and ethically.