Web scraping is the process of extracting data from websites automatically.
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Extract all paragraph texts
paragraphs = [p.get_text() for p in soup.find_all('p')]
print(paragraphs)
# Extract all links
links = [a['href'] for a in soup.find_all('a', href=True)]
print(links)
Python offers several frameworks for web development:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
# Typically involves multiple files
# Command to start a new project:
# django-admin startproject mysite
# Key components:
# - Models (database)
# - Views (business logic)
# - Templates (presentation)
# - URLs (routing)
Python is the dominant language for AI/ML with these key libraries:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
# Load data
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2)
# Train model
model = RandomForestClassifier()
model.fit(X_train, y_train)
# Evaluate
print("Accuracy:", model.score(X_test, y_test))
import tensorflow as tf
# Simple neural network
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
Typical data science process with Python: