scrap url base to set url's strcuture
solution adapts the best way to scrap content
solution shows links tree or numbered list and user choose or quit
user can select links to scrap by numbers
solution shows scrapped content as a 200 word preview
solution ask to user if wants to save in formated text
outout must include title, url and content
Assistant
Certainly! Below is a Python script that fulfills the requirements you've outlined. This script allows you to scrape a base URL, display the links found on that page in a numbered list, allow the user to select specific links to scrape further, show a 200-word preview of the selected content, and optionally save the scraped information to a formatted text file.
Dependencies
Before running the script, ensure you have the necessary Python packages installed. You can install them using pip:
bash
pip install requests beautifulsoup4
Python Script
python
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import sys
def get_links(base_url):
"""
Fetches the base URL and extracts all unique links.
Returns a list of tuples containing link text and absolute URLs.
"""
try:
response = requests.get(base_url)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error fetching {base_url}: {e}")
return []
soup = BeautifulSoup(response.text, 'html.parser')
links = set()
for a_tag in soup.find_all('a', href=True):
href = a_tag.get('href')
# Construct absolute URL
absolute_url = urljoin(base_url, href)
# Optional: Filter to same domain
if urlparse(absolute_url).netloc == urlparse(base_url).netloc:
link_text = a_tag.get_text(strip=True) or absolute_url
links.add((link_text, absolute_url))
return sorted(links, key=lambda x: x[0])
def display_links(links):
"""
Displays the list of links in a numbered format.
"""
if not links:
print("No links found.")
return
print("\nLinks found:")
for idx, (text, url) in enumerate(links, 1):
print(f"{idx}. {text} - {url}")
print()
def get_user_selection(max_num):
"""
Prompts the user to select links by their number.
Returns a list of selected indices.
"""
while True:
user_input = input("Enter link numbers to scrape separated by commas (or 'q' to quit): ")
if user_input.lower() == 'q':
return None
try:
selections = user_input.split(',')
indices = [int(num.strip()) for num in selections]
if all(1 <= num <= max_num for num in indices):
return list(set(indices)) # Remove duplicates
else:
print(f"Please enter numbers between 1 and {max_num}.")
except ValueError:
print("Invalid input. Please enter numbers separated by commas.")
def scrape_page(url):
"""
Scrapes the given URL and extracts the title, URL, and first 200 words of content.
Returns a dictionary with the scraped data.
"""
try:
response = requests.get(url)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error fetching {url}: {e}")
return None
soup = BeautifulSoup(response.text, 'html.parser')
title_tag = soup.find('title')
title = title_tag.get_text(strip=True) if title_tag else 'No Title'
# Extract text from all <p> tags
paragraphs = soup.find_all('p')
text_content = ' '.join(p.get_text(strip=True) for p in paragraphs)
words = text_content.split()
preview = ' '.join(words[:200]) + ('...' if len(words) > 200 else '')
return {
'title': title,
'url': url,
'content': preview
}
def save_content(scraped_data, filename="scraped_content.txt"):
"""
Saves the scraped data to a formatted text file.
"""
try:
with open(filename, 'a', encoding='utf-8') as file:
file.write(f"Title: {scraped_data['title']}\n")
file.write(f"URL: {scraped_data['url']}\n")
file.write("Content:\n")
file.write(f"{scraped_data['content']}\n")
file.write("-" * 80 + "\n")
print(f"Content saved to {filename}\n")
except IOError as e:
print(f"Error saving to file: {e}")
def main():
print("=== Web Scraper ===")
base_url = input("Enter the base URL to scrape: ").strip()
if not base_url:
print("No URL entered. Exiting.")
sys.exit(1)
links = get_links(base_url)
if not links:
print("No links to process. Exiting.")
sys.exit(1)
display_links(links)
selections = get_user_selection(len(links))
if selections is None:
print("Exiting.")
sys.exit(0)
for idx in selections:
link_text, link_url = links[idx - 1]
print(f"\nScraping [{idx}] {link_text} - {link_url}")
scraped = scrape_page(link_url)
if scraped:
print(f"\nTitle: {scraped['title']}")
print(f"URL: {scraped['url']}")
print(f"Content Preview:\n{scraped['content']}\n")
while True:
save_input = input("Do you want to save this content? (y/n): ").lower()
if save_input == 'y':
save_content(scraped)
break
elif save_input == 'n':
print("Content not saved.\n")
break
else:
print("Please enter 'y' or 'n'.")
print("All selected links have been processed.")
if __name__ == "__main__":
main()
How the Script Works
Prompt for Base URL: When you run the script, it will prompt you to enter the base URL you'd like to scrape.
Extract Links: The script fetches the content of the base URL and extracts all unique links (<a> tags with href attributes) that belong to the same domain as the base URL.
Display Links: It displays the extracted links in a numbered list showing both the link text and the absolute URL.
User Selection: You can select which links to scrape by entering the corresponding numbers separated by commas (e.g., 1,3,5). Entering q will quit the script.
Scrape Selected Links: For each selected link, the script fetches the page, extracts the title, URL, and a 200-word preview of the content (aggregated from all <p> tags).
Preview and Save: It displays the scraped information and asks if you want to save it. If you choose to save, the data is appended to a file named scraped_content.txt in a formatted manner.
Completion: After processing all selected links, the script informs you that all selected links have been processed.
Notes
Relative URLs: The script handles relative URLs by converting them to absolute URLs based on the base URL provided.
Same Domain Filtering: To maintain relevance, the script only includes links that belong to the same domain as the base URL. You can modify this behavior by adjusting the get_links function.
Error Handling: The script includes basic error handling for network issues and invalid user inputs.
Extensibility: You can further enhance the script by adding features such as recursive scraping, different content extraction techniques, or exporting to other formats like JSON or CSV.
Example Usage
code
=== Web Scraper ===
Enter the base URL to scrape: https://example.com
Links found:
1. Home - https://example.com/
2. About Us - https://example.com/about
3. Contact - https://example.com/contact
4. Blog - https://example.com/blog
Enter link numbers to scrape separated by commas (or 'q' to quit): 2,4
Scraping [2] About Us - https://example.com/about
Title: About Us - Example Company
URL: https://example.com/about
Content Preview:
[200-word preview of the About Us page content]
Do you want to save this content? (y/n): y
Content saved to scraped_content.txt
Scraping [4] Blog - https://example.com/blog
Title: Blog - Example Company
URL: https://example.com/blog
Content Preview:
[200-word preview of the Blog page content]
Do you want to save this content? (y/n): n
Content not saved.
All selected links have been processed.
This script provides a solid foundation for web scraping tasks and can be customized further based on your specific needs.