從零開始用 Python 爬蟲采集網絡數據(手把手實戰(zhàn)教程)
作者:用戶007
Python爬蟲可以自動采集數據,大大提高效率。本文將從最基礎的爬蟲原理開始,手把手教你寫出實用的爬蟲。
互聯網上有海量數據,但如果一條條手工復制粘貼,效率太低。Python爬蟲可以自動采集數據,大大提高效率。但爬蟲不是"黑科技",也不是"非法工具",它就是一個數據采集工具。只要遵守網站的robots.txt規(guī)則,尊重網站權益,爬蟲就是完全合法的。本文將從最基礎的爬蟲原理開始,手把手教你寫出實用的爬蟲。

爬蟲的核心原理
爬蟲就三個步驟:
- 發(fā)送請求:向網站發(fā)送HTTP請求
- 獲取內容:接收網站返回的HTML內容
- 解析數據:從HTML中提取需要的數據
# 爬蟲三部曲演示
import requests
from bs4 import BeautifulSoup
# 第一步:發(fā)送請求
url = 'http://example.com'
response = requests.get(url)
# 第二步:獲取內容
html_content = response.text
# 第三步:解析數據
soup = BeautifulSoup(html_content, 'html.parser')實戰(zhàn)1:爬取豆瓣電影評分
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 訪問豆瓣Top250
url = 'https://movie.douban.com/top250'
# 設置請求頭(偽裝瀏覽器)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取電影信息
movies_data = []
for item in soup.find_all('div', class_='item'):
# 提取電影名
title = item.find('span', class_='title').text
# 提取評分
rating = item.find('span', class_='rating_num').text
# 提取年份和國家
info = item.find('p', class_='').text.strip()
movies_data.append({
'電影名': title,
'評分': rating,
'信息': info
})
print(f"已爬?。簕title} 評分:{rating}")
# 保存為Excel
df = pd.DataFrame(movies_data)
df.to_excel('豆瓣TOP250.xlsx', index=False)
print("? 數據已保存")實戰(zhàn)2:爬取天氣信息
import requests
import json
# 使用天氣API(不需要登錄)
cities = ['Beijing', 'Shanghai', 'Guangzhou']
weather_data = []
for city in cities:
# 使用免費的天氣API
url = f'https://api.weatherapi.com/v1/current.json'
params = {
'q': city,
'aqi': 'yes'
}
try:
response = requests.get(url, params=params, timeout=5)
data = response.json()
weather_info = {
'城市': city,
'溫度': data['current']['temp_c'],
'天氣': data['current']['condition']['text'],
'濕度': data['current']['humidity'],
}
weather_data.append(weather_info)
print(f"{city}: {weather_info['天氣']}, {weather_info['溫度']}℃")
except Exception as e:
print(f"爬取{city}失?。簕e}")
# 保存數據
import csv
with open('weather.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=['城市', '溫度', '天氣', '濕度'])
writer.writeheader()
writer.writerows(weather_data)實戰(zhàn)3:爬取新聞標題和鏈接
import requests
from bs4 import BeautifulSoup
# 爬取新聞網站
url = 'https://news.sina.com.cn/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
# 查找所有新聞
news_items = soup.find_all('a', class_='news-link')[:10] # 取前10條
print("最新新聞:")
for i, item in enumerate(news_items, 1):
title = item.text.strip()
link = item.get('href')
print(f"{i}. {title}")
print(f" 鏈接:{link}\n")爬蟲的優(yōu)秀實踐和注意事項
(1) 檢查robots.txt
import requests
# 檢查網站是否允許爬蟲
url = 'https://example.com/robots.txt'
response = requests.get(url)
print(response.text)
# 根據robots.txt規(guī)則調整爬蟲(2) 設置請求延遲
import time
import requests
urls = ['url1', 'url2', 'url3']
for url in urls:
response = requests.get(url)
# 處理數據...
time.sleep(2) # 等待2秒再發(fā)送下一個請求,避免頻繁訪問(3) 處理異常
import requests
from requests.exceptions import Timeout, ConnectionError
url = 'https://example.com'
try:
response = requests.get(url, timeout=5) # 5秒超時
response.raise_for_status() # 檢查HTTP狀態(tài)
except Timeout:
print("請求超時")
except ConnectionError:
print("連接錯誤")
except requests.exceptions.HTTPError as e:
print(f"HTTP錯誤:{e}")(4) 使用Cookie處理需要登錄的網站
import requests
url = 'https://example.com/login'
# 登錄
login_data = {
'username': 'your_username',
'password': 'your_password'
}
session = requests.Session()
session.post(url, data=login_data)
# 登錄后訪問受保護的頁面
response = session.get('https://example.com/protected')
print(response.text)爬蟲的法律和倫理
? 合法使用爬蟲:
- 爬取公開數據
- 遵守robots.txt
- 不給服務器造成壓力
- 標注數據來源
? 不應該做的事:
- 爬取個人隱私信息
- 頻繁請求導致網站宕機
- 繞過反爬蟲機制
- 爬取有版權保護的內容
結尾
爬蟲是強大的工具,但也要負責任地使用。一個成熟的爬蟲應該是不過度占用帶寬、不繞過反爬蟲機制、不爬取隱私數據。當你學會了基礎爬蟲后,可以進階學習Scrapy框架來處理大規(guī)模數據采集。
責任編輯:趙寧寧
來源:
Python數智工坊




















