Certainly! Below is a Python script that allows a user to input a URL, scrapes the webpage to extract all the hyperlinks (<a> tags with href attributes), formats them, and saves them into a single text file. The script uses the requests library to fetch the webpage content and BeautifulSoup from the bs4 library to parse the HTML.
Prerequisites
Before running the script, ensure you have Python installed on your machine. Additionally, you'll need to install the required libraries:
pip install requests beautifulsoup4
The Python Script
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import os
def get_user_url():
"""Prompt the user to enter a URL and validate it."""
while True:
url = input("Enter the URL to scrape: ").strip()
if not url:
print("URL cannot be empty. Please try again.")
continue
# Basic validation
parsed = urlparse(url)
if not parsed.scheme:
url = 'http://' + url # Default to http if no scheme provided
parsed = urlparse(url)
if not parsed.netloc:
print("Invalid URL. Please enter a valid URL (e.g., https://www.example.com).")
continue
return url
def fetch_page(url):
"""Fetch the content of the page at the given URL."""
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors
return response.text
except requests.exceptions.RequestException as e:
print(f"Error fetching the URL: {e}")
return None
def extract_links(html_content, base_url):
"""Extract and format all unique absolute URLs from the HTML content."""
soup = BeautifulSoup(html_content, 'html.parser')
links = set()
for a_tag in soup.find_all('a', href=True):
href = a_tag['href'].strip()
# Convert relative URLs to absolute URLs
absolute_url = urljoin(base_url, href)
# Optional: Exclude mailto:, javascript:, tel:, etc.
parsed_href = urlparse(absolute_url)
if parsed_href.scheme in ['http', 'https']:
links.add(absolute_url)
return sorted(links)
def save_links_to_file(links, filename='extracted_links.txt'):
"""Save the list of links to a text file."""
try:
with open(filename, 'w', encoding='utf-8') as f:
for link in links:
f.write(link + '\n')
print(f"Successfully saved {len(links)} links to '{filename}'.")
except IOError as e:
print(f"Error writing to file: {e}")
def main():
url = get_user_url()
print(f"Fetching content from: {url}")
html_content = fetch_page(url)
if html_content is None:
return
print("Extracting links...")
links = extract_links(html_content, url)
if not links:
print("No valid links found on the page.")
return
save_links_to_file(links)
if __name__ == "__main__":
main()
How It Works
-
User Input and Validation (get_user_url)
- The script prompts the user to input a URL.
- It performs basic validation to ensure the URL is not empty and has a valid scheme (
http or https). If the scheme is missing, it defaults to http://.
- If the URL is invalid, it prompts the user to enter it again.
-
Fetching the Webpage Content (fetch_page)
- Uses the
requests library to send an HTTP GET request to the provided URL.
- If the request is successful (status code 200), it returns the HTML content.
- Handles exceptions such as connection errors, timeouts, and invalid HTTP responses.
-
Extracting Links (extract_links)
- Parses the fetched HTML content using
BeautifulSoup.
- Iterates through all
<a> tags that have an href attribute.
- Converts relative URLs to absolute URLs using
urljoin.
- Filters out non-HTTP(s) links like
mailto:, javascript:, etc.
- Stores the links in a
set to ensure uniqueness and then sorts them.
-
Saving Links to a Text File (save_links_to_file)
- Writes each extracted link to a text file named
extracted_links.txt, one URL per line.
- Reports success or any file I/O errors encountered.
-
Main Function (main)
- Orchestrates the flow by calling the above functions in sequence.
Running the Script
-
Save the Script
Save the above script to a file, for example, web_scraper.py.
-
Execute the Script
Open your terminal or command prompt, navigate to the directory containing web_scraper.py, and run:
python web_scraper.py
-
Provide the URL
When prompted, enter the URL of the website you want to scrape. For example:
Enter the URL to scrape: https://www.example.com
-
Result
- The script will fetch the webpage, extract all the unique HTTP(s) links, and save them to
extracted_links.txt in the same directory.
- It will display a success message with the number of links saved.
Example Output
Enter the URL to scrape: https://www.example.com
Fetching content from: https://www.example.com
Extracting links...
Successfully saved 5 links to 'extracted_links.txt'.
extracted_links.txt Content
https://www.iana.org/domains/example
https://www.example.com/about
https://www.example.com/contact
https://www.example.com/privacy
https://www.example.com/services
Notes and Considerations
-
Respect Robots.txt and Website Policies: Before scraping any website, ensure you have permission to do so and that you're respecting the website’s robots.txt file and terms of service.
-
Handling JavaScript-Rendered Links: This script works for static HTML content. If the webpage loads links dynamically using JavaScript, consider using tools like Selenium or Playwright to render JavaScript.
-
Rate Limiting: For scraping multiple pages or large websites, implement rate limiting to avoid overwhelming the server and to prevent being blocked.
-
Enhancements:
- Command-Line Arguments: Modify the script to accept the URL and output file as command-line arguments using the
argparse library.
- Recursive Scraping: Extend the script to follow links and scrape multiple pages recursively.
- Filtering: Allow users to filter links based on patterns or domains.
Conclusion
This script provides a simple and effective way to extract all HTTP and HTTPS links from a given webpage and save them to a text file. It's a good starting point for more advanced web scraping projects. Always ensure that your scraping activities comply with the website's policies and legal guidelines.