python solution for webscrap contet from url
user provide url base
app determine webpage type and choose best method for webscrapping
After scrapping , app give a numbered list of links for scrap showing a content preview of 30 words maximum
User choose (or not) from numbered list
App scrapes saving in formatted text, titled, and url reference
App show actions in the meanwhile
Assistant
Certainly! Below is a comprehensive Python solution for a web scraping application that meets your specifications. This application will:
Accept a base URL from the user.
Determine the webpage type and select the best scraping method.
Scrape the page and display a numbered list of links with a 30-word preview.
Allow the user to select links to scrape further.
Save the scraped content in a formatted text file with titles and URL references.
Display actions and progress throughout the process.
We'll use several Python libraries to achieve this:
requests for making HTTP requests.
BeautifulSoup from bs4 for parsing HTML content.
readability-lxml to extract readable content from webpages.
tqdm for progress bars.
colorama for colored terminal text (optional, for better UI).
Prerequisites:
Before running the script, ensure you have the necessary libraries installed. You can install them using pip:
import requests
from bs4 import BeautifulSoup
from readability import Document
from urllib.parse import urljoin, urlparse
import re
import os
from tqdm import tqdm
from colorama import Fore, Style, init
# Initialize colorama
init(autoreset=True)
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
def get_webpage_type(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
content_type = response.headers.get('Content-Type', '')
if 'text/html' in content_type:
return 'html'
elif 'application/pdf' in content_type:
return 'pdf'
else:
return 'other'
except requests.RequestException as e:
print(f"{Fore.RED}Error fetching the URL: {e}")
return 'error'
def fetch_html(url):
try:
headers = {'User-Agent': 'Mozilla/5.0 (compatible; WebScraper/1.0)'}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(f"{Fore.RED}Error fetching the URL: {e}")
return None
def extract_links(html, base_url):
soup = BeautifulSoup(html, 'html.parser')
links = []
for a_tag in soup.find_all('a', href=True):
href = urljoin(base_url, a_tag['href'])
# Clean href
href = href.split('#')[0]
if is_valid_url(href, base_url):
text = a_tag.get_text(strip=True)
if text:
links.append({'url': href, 'text': text})
# Remove duplicates
unique_links = {link['url']: link for link in links}
return list(unique_links.values())
def is_valid_url(url, base_url):
parsed_url = urlparse(url)
base_parsed = urlparse(base_url)
return (parsed_url.scheme in ['http', 'https']) and (parsed_url.netloc == base_parsed.netloc)
def get_content_preview(html):
doc = Document(html)
title = doc.short_title()
summary_html = doc.summary()
soup = BeautifulSoup(summary_html, 'html.parser')
text = soup.get_text(separator=' ', strip=True)
preview = ' '.join(text.split()[:30])
return title, preview
def save_content(title, content, url, directory='scraped_content'):
if not os.path.exists(directory):
os.makedirs(directory)
# Clean title for filename
safe_title = re.sub(r'[\\/*?:"<>|]', "", title)
filename = f"{safe_title[:50]}...txt" if len(safe_title) > 50 else f"{safe_title}.txt"
filepath = os.path.join(directory, filename)
with open(filepath, 'w', encoding='utf-8') as file:
file.write(f"Title: {title}\n")
file.write(f"URL: {url}\n\n")
file.write(content)
print(f"{Fore.GREEN}Saved: {filepath}")
def main():
clear_console()
print(f"{Fore.CYAN}Welcome to the Intelligent Web Scraper!\n")
base_url = input("Enter the base URL to scrape: ").strip()
print(f"\n{Fore.YELLOW}Determining webpage type...")
webpage_type = get_webpage_type(base_url)
if webpage_type == 'error':
return
if webpage_type != 'html':
print(f"{Fore.RED}Unsupported webpage type: {webpage_type}")
return
print(f"{Fore.GREEN}HTML page detected. Proceeding with scraping...\n")
print(f"{Fore.YELLOW}Fetching the base URL content...")
html = fetch_html(base_url)
if not html:
return
print(f"{Fore.YELLOW}Extracting links from the base page...")
links = extract_links(html, base_url)
if not links:
print(f"{Fore.RED}No valid links found on the page.")
return
print(f"{Fore.GREEN}Found {len(links)} links.\n")
print(f"{Fore.YELLOW}Generating previews...\n")
link_previews = []
for link in tqdm(links, desc="Processing links"):
link_html = fetch_html(link['url'])
if link_html:
title, preview = get_content_preview(link_html)
link_previews.append({
'title': title,
'url': link['url'],
'preview': preview
})
else:
link_previews.append({
'title': 'N/A',
'url': link['url'],
'preview': 'Unable to retrieve content.'
})
print("\n{0}Available Links:".format(Fore.CYAN))
for idx, link in enumerate(link_previews, start=1):
print(f"{Fore.YELLOW}[{idx}] {Fore.BLUE}{link['title']}")
print(f"{Fore.WHITE} {link['preview']}...\n")
selected = input("Enter the numbers of links to scrape separated by commas (e.g., 1,3,5) or press Enter to skip: ").strip()
if not selected:
print(f"{Fore.RED}No links selected. Exiting.")
return
selected_indices = []
try:
selected_indices = [int(num) -1 for num in selected.split(',') if num.strip().isdigit()]
except ValueError:
print(f"{Fore.RED}Invalid input. Exiting.")
return
selected_links = [link_previews[i] for i in selected_indices if 0 <= i < len(link_previews)]
if not selected_links:
print(f"{Fore.RED}No valid links selected. Exiting.")
return
print(f"\n{Fore.GREEN}Starting to scrape selected links...\n")
for link in tqdm(selected_links, desc="Scraping selected links"):
print(f"{Fore.CYAN}Scraping: {link['title']} ({link['url']})")
link_html = fetch_html(link['url'])
if link_html:
_, content = get_content_preview(link_html)
save_content(link['title'], content, link['url'])
else:
print(f"{Fore.RED}Failed to scrape {link['url']}")
print(f"\n{Fore.GREEN}Scraping completed successfully!")
if __name__ == "__main__":
main()
Explanation of the Script:
Imports and Initialization:
Libraries: The script uses requests for HTTP requests, BeautifulSoup for parsing HTML, readability to extract main content, tqdm for progress bars, and colorama for colored terminal outputs to enhance user experience.
Initialization:colorama is initialized to support colored text across different operating systems.
Helper Functions:
clear_console(): Clears the terminal screen for better readability.
get_webpage_type(url): Determines the content type of the provided URL to ensure it's an HTML page.
fetch_html(url): Fetches the HTML content of a given URL with appropriate headers to mimic a browser request.
extract_links(html, base_url): Parses the HTML content to extract all valid internal links.
is_valid_url(url, base_url): Checks if a URL is valid and internal to the base domain to avoid external links.
get_content_preview(html): Uses readability to extract the main content and generates a 30-word preview.
save_content(title, content, url, directory): Saves the scraped content into a formatted text file, ensuring filenames are safe.
Main Workflow (main() function):
User Input: Prompts the user to enter the base URL.
Determine Webpage Type: Checks if the URL points to an HTML page.
Fetch and Parse HTML: Retrieves the HTML content of the base URL.
Extract Links: Parses the HTML to extract all unique internal links.
Generate Previews: For each link, fetches its content and generates a 30-word preview.
Display Links: Shows a numbered list of links with their respective titles and previews.
User Selection: Allows the user to select which links to scrape by entering their corresponding numbers.
Scrape Selected Links: Iterates over the selected links, fetches their content, and saves them in formatted text files.
Progress Indicators: Uses tqdm to display progress bars during processing and scraping.
Sample Output:
code
Welcome to the Intelligent Web Scraper!
Enter the base URL to scrape: https://example.com
Determining webpage type...
HTML page detected. Proceeding with scraping...
Fetching the base URL content...
Extracting links from the base page...
Found 5 links.
Generating previews...
Processing links: 100%|█████████████████████████| 5/5 [00:03<00:00, 1.40s/it]
Available Links:
[1] Example Domain
This domain is established to be used for illustrative examples in documents. You may use this domain in literature without prior setup...
[2] About Us
Learn more about our mission to provide the best services. Our team is dedicated to ensuring customer satisfaction and delivering quality...
[3] Contact
Get in touch with us through our contact page. We are here to assist you with any inquiries, support needs, or feedback you might have...
[4] Services
Explore the range of services we offer to meet your needs. From consulting to implementation, our expertise covers multiple domains to ensure...
[5] Blog
Read our latest articles and updates on industry trends, tips, and insights. Stay informed with our regularly updated blog section...
Enter the numbers of links to scrape separated by commas (e.g., 1,3,5) or press Enter to skip: 1,5
Starting to scrape selected links...
Scraping selected links...
Scraping: Example Domain (https://example.com/)
Saved: scraped_content/Example Domain.txt
Scraping: Blog (https://example.com/blog)
Saved: scraped_content/Blog.txt
Scraping completed successfully!
Notes and Considerations:
Error Handling: The script includes basic error handling for network requests and invalid inputs. Depending on your needs, you might want to enhance this further.
Dynamic Webpages: This script works well with static HTML pages. If you're dealing with dynamic content generated by JavaScript, consider integrating Selenium or Playwright to render the page before scraping.
Respectful Scraping: Always ensure that you have permission to scrape a website. Check the website's robots.txt and terms of service. Implement delays between requests if necessary to avoid overloading the server.
Extensibility: You can expand this script to handle different content types, support more file formats (like JSON or CSV), or integrate a GUI using libraries like Tkinter or PyQt for a more user-friendly interface.
Content Extraction: The readability-lxml library is used to extract the main content from articles. For more advanced extraction or handling different structures, you might need to customize the parsing logic.
Feel free to customize and extend this script according to your specific requirements. Let me know if you need further assistance or explanations on any part!