Here's a simple Python web scraping script using requests and BeautifulSoup:
python
import requests
from bs4 import BeautifulSoup
import time
import csv
def scrape_website(url, delay=1):
"""
Basic web scraper that extracts titles and links from a webpage
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
try:
# Send GET request
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status() # Raises an exception for bad status codes
# Parse HTML content
soup = BeautifulSoup(response.content, 'html.parser')
# Extract data
results = []
# Get page title
page_title = soup.find('title')
if page_title:
print(f"Page Title: {page_title.get_text().strip()}")
# Extract all links
links = soup.find_all('a', href=True)
for link in links[:10]: # Limit to first 10 links
text = link.get_text().strip()
href = link['href']
if text and href:
results.append({
'text': text,
'url': href
})
# Add delay to be respectful
time.sleep(delay)
return results
except requests.RequestException as e:
print(f"Error fetching {url}: {e}")
return []
except Exception as e:
print(f"Error parsing content: {e}")
return []
def save_to_csv(data, filename='scraped_data.csv'):
"""Save scraped data to CSV file"""
if data:
with open(filename, 'w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=['text', 'url'])
writer.writeheader()
writer.writerows(data)
print(f"Data saved to {filename}")
# Example usage
if __name__ == "__main__":
# Example URL - replace with your target
target_url = "https://httpbin.org/html" # Safe test URL
print(f"Scraping: {target_url}")
scraped_data = scrape_website(target_url)
if scraped_data:
print(f"\nFound {len(scraped_data)} links:")
for item in scraped_data:
print(f"Text: {item['text'][:50]}...")
print(f"URL: {item['url']}")
print("-" * 50)
save_to_csv(scraped_data)
else:
print("No data scraped")
Installation requirements:
bash
pip install requests beautifulsoup4 lxml
Key features of this scraper:
Error handling: Catches network and parsing errors
User agent: Mimics a real browser to avoid blocking
Rate limiting: Includes delays between requests
Data extraction: Gets page titles and links
CSV export: Saves results to a file
Timeout: Prevents hanging on slow responses
Important considerations:
Always check the website's robots.txt file (e.g., example.com/robots.txt)
Respect the site's terms of service
Add appropriate delays between requests
Consider using rotating user agents for larger projects
For JavaScript-heavy sites, you might need Selenium instead
To customize for your needs:
Modify the CSS selectors in soup.find_all()
Adjust the delay between requests
Add more sophisticated data extraction logic
Implement retry mechanisms for failed requests
Would you like me to modify this for a specific type of data or website structure?