A simple text based browser I want to add screenshots any help?
import requests
from bs4 import BeautifulSoup
import sys
import os
class IrisFoxBrowser:
def __init__(self):
self.history = []
self.user_agent = "Iris Fox/1.0 (Linux)"
self.favorites_file = "favorites.txt"
self.favorites = self.load_favorites()
def load_favorites(self):
if os.path.exists(self.favorites_file):
with open(self.favorites_file, "r") as file:
return [line.strip() for line in file.readlines()]
return []
def save_favorite(self, url):
if url not in self.favorites:
self.favorites.append(url)
with open(self.favorites_file, "a") as file:
file.write(url + "\n")
print(f"Saved to favorites: {url}")
else:
print(f"{url} is already in favorites.")
def list_favorites(self):
if self.favorites:
print("Favorites:")
for idx, url in enumerate(self.favorites):
print(f"[{idx}] {url}")
else:
print("No favorite sites saved.")
def fetch_page(self, url):
try:
headers = {'User-Agent': self.user_agent}
response = requests.get(url, headers=headers)
response.raise_for_status()
# Save URL to history for navigation
self.history.append(url)
# Parse the page content
soup = BeautifulSoup(response.content, 'html.parser')
return soup
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return None
def display_text(self, soup):
if soup:
text = soup.get_text()
print(text.strip())
else:
print("No content to display.")
def list_links(self, soup):
if soup:
links = soup.find_all('a', href=True)
for idx, link in enumerate(links):
print(f"[{idx}] {link.text.strip()}: {link['href']}")
else:
print("No links found.")
def follow_link(self, index, soup):
try:
links = soup.find_all('a', href=True)
if 0 <= index < len(links):
new_url = links[index]['href']
# Ensure the URL is absolute
if new_url.startswith('http'):
return new_url
else:
print("Invalid URL format. Skipping.")
else:
print("Invalid link index.")
except Exception as e:
print(f"Error following link: {e}")
return None
def go_back(self):
if len(self.history) > 1:
self.history.pop() # Remove current page
return self.history.pop() # Return previous page
else:
print("No previous page to go back to.")
return None
def search_text(self, soup, keyword):
if soup:
text = soup.get_text()
if keyword.lower() in text.lower():
print(f"Found '{keyword}' in the page!")
else:
print(f"'{keyword}' not found in the page.")
else:
print("No content to search.")
def google_search(self, query):
search_url = f"https://www.google.com/search?q={query.replace(' ', '+')}"
headers = {'User-Agent': self.user_agent}
try:
response = requests.get(search_url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
links = soup.find_all('a', href=True)
# Display top search results (clean URLs)
result_links = [link for link in links if "/url?q=" in link['href']]
if result_links:
for idx, link in enumerate(result_links[:10]): # Top 10 results
clean_url = link['href'].split("/url?q=")[1].split("&")[0]
print(f"[{idx}] {clean_url}")
else:
print("No search results found.")
except requests.exceptions.RequestException as e:
print(f"Error during Google search: {e}")
if __name__ == "__main__":
browser = IrisFoxBrowser()
while True:
command = input("Iris Fox > ").strip()
# Command to fetch a page
if command.startswith("open "):
url = command.split("open ", 1)[1]
page = browser.fetch_page(url)
browser.display_text(page)
# Command to list links on the current page
elif command == "links":
page = browser.fetch_page(browser.history[-1])
browser.list_links(page)
# Command to follow a link by index
elif command.startswith("follow "):
try:
index = int(command.split("follow ", 1)[1])
page = browser.fetch_page(browser.history[-1])
new_url = browser.follow_link(index, page)
if new_url:
new_page = browser.fetch_page(new_url)
browser.display_text(new_page)
except ValueError:
print("Invalid link index.")
# Command to go back to the previous page
elif command == "back":
previous_url = browser.go_back()
if previous_url:
previous_page = browser.fetch_page(previous_url)
browser.display_text(previous_page)
# Command to search for a keyword on the current page
elif command.startswith("search "):
keyword = command.split("search ", 1)[1]
page = browser.fetch_page(browser.history[-1])
browser.search_text(page, keyword)
# Command to change user-agent
elif command.startswith("user-agent "):
agent = command.split("user-agent ", 1)[1]
browser.user_agent = agent
print(f"User-agent changed to: {agent}")
# Command to save current URL to favorites
elif command == "save favorite":
if browser.history:
browser.save_favorite(browser.history[-1])
else:
print("No page loaded to save.")
# Command to list favorite sites
elif command == "favorites":
browser.list_favorites()
# Command to Google search
elif command.startswith("google "):
query = command.split("google ", 1)[1]
browser.google_search(query)
# Quit the browser
elif command == "quit":
print("Exiting Iris Fox.")
break
else:
print("Unknown command. Available commands: open <url>, links, follow <index>, back, search <keyword>, save favorite, favorites, google <query>, user-agent <agent>, quit")