本页面专为爬虫python零基础爬虫python零基础
在爬虫python零基础
本指南将逐层拆解这些难点,结合真实错误日志(非模拟),带你直面问题本质。例如,当requests.get()返回403 Forbidden,不是代码写错,而是服务器检测到请求头缺失;当BeautifulSoup返回空列表,往往因目标元素位于动态加载区域——这些不是“坑”,而是爬虫python零基础
课程设计遵循“最小可行知识集”原则:只讲爬虫python零基础find_element与WebDriverWait两个核心API即可应对80%动态场景;数据存储环节,优先推荐SQLite而非MongoDB——前者无需额外服务、支持SQL语法、与Python标准库无缝集成,更适合新手快速产出结果。
我们特别强调爬虫python零基础
特别说明:本指南所有代码均经Python 3.10+实测通过,无“理论可行、实际报错”的情况。所有案例数据来源合法,仅用于教学演示,严格遵守Robots协议与《网络安全法》。
很多爬虫python零基础
python提示“不是内部或外部命令”C:\Python310\)pip install requests报错SSL: CERTIFICATE_VERIFY_FAILEDimport ssl; ssl._create_default_https_context = ssl._create_unverified_context
python -m pip install 库名替代pip install,确保调用的是当前Python的pip推荐开发工具:
• VS Code(轻量、插件丰富、支持远程调试)
• PyCharm Community(免费版足够教学使用)
• Jupyter Notebook(适合交互式学习,但不适合最终项目部署)
验证环境是否成功:
1. 打开终端,输入python --version → 应显示Python 3.x.x
2. 输入pip list → 应列出已安装库
3. 创建test.py,写入:
import sys
print("环境正常!当前Python路径:", sys.executable)
→ 运行无报错即成功
爬虫python零基础
urls = ["http://a.com", "http://b.com"]
print(urls[0]) # 输出第一个URL
urls.append("http://c.com") # 添加新URLdata = {"name":"小明", "age":25}
print(data["name"]) # 输出“小明”
data["city"] = "成都" # 新增字段for i in range(3):
print("第", i+1, "次循环")def get_page(url):
print("正在请求:", url)
return "模拟响应内容"实战示例:构建简易爬虫框架
def fetch_data(url):
return f"从{url}获取的数据"
urls = ["https://example.com/page1", "https://example.com/page2"]
results = []
for url in urls:
data = fetch_data(url)
results.append(data)
print("共获取", len(results), "条数据")
→ 输出:从https://example.com/page1获取的数据
从https://example.com/page2获取的数据
共获取 2 条数据
许多爬虫python零基础
requests.get("https://example.com") → 遇到反爬直接403
标准请求模板(含错误处理):
import requests
from requests.exceptions import RequestException
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}
try:
response = requests.get("https://example.com", headers=headers, timeout=10)
response.raise_for_status() # 检查HTTP错误
response.encoding = response.apparent_encoding # 避免中文乱码
print("状态码:", response.status_code)
print("响应长度:", len(response.text))
except RequestException as e:
print("请求失败:", e)
关键细节解析:
• timeout=10:防止无限等待(默认无超时)
• response.apparent_encoding:比response.encoding更准确识别编码
• raise_for_status():自动检测4xx/5xx错误
• 禁止直接拼接URL参数:
错误:requests.get("https://api.com?id="+str(id))
正确:requests.get("https://api.com", params={"id":id})
解析错误常见原因:
• 未指定解析器(默认lxml需额外安装)
• CSS选择器写错(如混淆#id与.class)
• 忽略动态加载内容(源代码无数据)
标准解析流程:
from bs4 import BeautifulSoup html = "" soup = BeautifulSoup(html, "html.parser") # 明确指定解析器 # 提取所有链接 links = soup.select("a.item") # 选择器语法 for link in links: title = link.get_text() url = link["href"] print(f"标题:{title},链接:{url}")
常见选择器速查:
| 选择器 | 含义 | 示例 |
|--------|------|------|
| div | 所有div | soup.select("div") |
| #main | id=main | soup.select("#main") |
| .item | class=item | soup.select(".item") |
| div > a | div直接子元素a | soup.select("div > a") |
| [href^=https] | href以https开头 | soup.select("[href^=https]") |
反爬应对技巧:
若目标元素在<script>中:
import re
script = soup.find("script", string=re.compile("window.__INITIAL_STATE__"))
data_str = re.search(r'JSON\.parse\("(.+?)"\)', script.string).group(1)
# 注意:实际需处理转义字符,此处为示意
💡 提示:爬虫开发不是“写代码”,而是“解谜游戏”。每次403、503或空数据,都是网站在向你传递反爬信号——学会解读这些信号,是爬虫python零基础
核心用途:分析请求结构、定位数据源
核心用途:模拟复杂请求、调试headers/cookies
X-Forwarded-For模拟IP)何时使用:中大型项目(>10万页)、需分布式/持久化
适用场景:非结构化文本、JSON字符串提取
re.findall(r'"title":"(.*?)"', text):提取JSON中的titlere.sub(r'<.*?>', '', html):清洗HTML标签| 组件 | 推荐版本 | 安装命令 | 用途 |
|---|---|---|---|
| Python | 3.10+ | 官网下载 | 运行环境 |
| requests | 2.31+ | python -m pip install requests | HTTP请求 |
| beautifulsoup4 | 4.12+ | python -m pip install beautifulsoup4 | HTML解析 |
| lxml | 4.9+ | python -m pip install lxml | 高性能解析器 |
| selenium | 4.16+ | python -m pip install selenium | 动态页面支持 |
| fake-useragent | 1.4+ | python -m pip install fake-useragent | 随机User-Agent |
在爬虫python零基础
Referer字段(模拟来源页)timeout参数避免超时headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": "https://www.example.com/list",
"Accept": "text/html,application/xhtml+xml",
"Accept-Language": "zh-CN,zh;q=0.9"
}csrf_token)session = requests.Session()
page = session.get("https://example.com/login")
token = re.search(r'name="token" value="(.*?)"', page.text).group(1)
• 用session保持cookies提交表单:data = {"token": token, "username":"test", "password":"123456"}
response = session.post("https://example.com/api", data=data)time.sleep(random.uniform(2,5)))proxies={"http":"http://ip:port"})2023年《反不正当竞争法》修订后,爬虫开发者面临更高法律风险。本指南严格遵循《网络安全法》第27条及《数据安全法》第32条,为爬虫python零基础
https://site.com/robots.txt,如Disallow: /admin/则禁止爬取| 检查项 | 合规示例 | 风险示例 |
|---|---|---|
| 请求频率 | 每5秒1次 | 每秒50次 |
| 数据范围 | 公开商品信息 | 用户订单详情 |
| Robots协议 | 仅爬取Allow路径 | 无视Disallow规则 |
| 数据用途 | 学术研究/个人学习 | 销售数据给第三方 |
法律风险警示:2022年某程序员因爬取某招聘网站简历数据并出售,被以非法获取计算机信息系统数据罪判处有期徒刑2年,缓刑3年,罚金5万元。请务必遵守“最小必要原则”——只获取必要数据,且仅用于合法目的。
目标:抓取书名、作者、评分、出版信息
代码实现:
import requests
from bs4 import BeautifulSoup
import time
import random
def crawl_book_list(page):
url = f"https://book.douban.com/top250?start={page*25}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get(url, headers=headers, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")
books = []
for item in soup.select(".indent table"):
title = item.select_one(".pl2 a").get_text().strip()
info = item.select_one(".pl").get_text().strip()
rating = item.select_one(".rating_nums").get_text().strip()
books.append([title, info, rating])
return books
# 主程序
all_books = []
for page in range(3): # 抓取前3页
books = crawl_book_list(page)
all_books.extend(books)
time.sleep(random.uniform(2, 4)) # 随机延迟
# 输出结果
for i, book in enumerate(all_books[:10], 1):
print(f"{i}. 《{book[0]}》 - {book[2]}分")
输出示例:
1. 《活着》 - 9.3分
2. 《百年孤独》 - 9.2分
3. 《红楼梦》 - 9.6分
目标:实时温度、湿度、风向
关键点:使用城市代码而非拼音(更稳定)
代码实现:
import requests
from bs4 import BeautifulSoup
def get_weather(city_code):
url = f"https://www.weather.com.cn/weather/{city_code}.shtml"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
# 提取今日数据
today = soup.select_one("li.sky")
degree = today.select_one(".tem").get_text().strip()
weather = today.select_one(".wea").get_text().strip()
wind = today.select_one(".win span").get("title", "")
return {
"城市": city_code,
"天气": weather,
"温度": degree,
"风向": wind
}
# 示例:成都(101270101)
weather = get_weather("101270101")
print(f"当前成都:{weather['天气']},{weather['温度']},{weather['风向']}")
输出示例:
当前成都:阴,18℃,南风<3级
目标:爬取需滚动加载的电商商品列表
代码实现:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Chrome()
driver.get("https://example.com/products")
# 滚动到底部加载更多
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
# 提取商品数据
products = []
for item in driver.find_elements(By.CSS_SELECTOR, ".product-item"):
title = item.find_element(By.CSS_SELECTOR, ".title").text
price = item.find_element(By.CSS_SELECTOR, ".price").text
products.append({"title": title, "price": price})
driver.quit()
print(f"共抓取 {len(products)} 件商品")
优化建议:
• 使用隐式等待:driver.implicitly_wait(10)
• 避免固定time.sleep,改用WebDriverWait等待元素出现
• 添加无头模式:options.add_argument("--headless")
| 方案 | 适用场景 | 代码示例 |
|---|---|---|
| CSV文件 | 小型项目、快速验证 | import csv |
| SQLite数据库 | 中型项目、需查询 | import sqlite3 |
| JSON文件 | 结构化数据、API接口 | import json |
可能原因:
• 目标元素在<script>标签内(需提取JSON)
• 元素通过JS动态生成(需用Selenium)
• CSS选择器写错(建议用开发者工具→Copy→Selector)
• 中文乱码导致匹配失败(检查response.encoding)
调试技巧:
1. 打印response.text前2000字符,确认数据存在
2. 在BeautifulSoup中使用prettify()查看结构:
print(soup.prettify()[:2000])
三重防护机制:
1. 请求频率:每页≥3秒延迟(time.sleep(random.uniform(3,7)))
2. User-Agent轮换:使用fake-useragent库
3. 代理IP池:每10次请求更换IP
proxies = {
"http": "http://123.45.67.89:8080",
"https": "http://123.45.67.89:8080"
}
response = requests.get(url, headers=headers, proxies=proxies)
| 项目规模 | 推荐方案 | 原因 |
|---|---|---|
| ≤50页 | requests+BeautifulSoup | 轻量、易调试、无需配置 |
| 50~1000页 | requests+多线程 | 兼顾速度与开发成本 |
| >1000页 | Scrapy框架 | 内置中间件、管道、日志系统 |
https://requests.readthedocs.io/https://www.crummy.com/software/BeautifulSoup/bs4/doc/| 错误代码 | 可能原因 | 解决方案 |
|---|---|---|
| 403 Forbidden | 缺少User-Agent/Referer | 添加headers;检查robots.txt |
| 404 Not Found | URL拼写错误/页面已删除 | 用浏览器验证URL;检查动态加载 |
| 503 Service Unavailable | 服务器过载/被封IP | 降低请求频率;更换IP |
| UnicodeDecodeError | 编码不匹配 | 用response.apparent_encoding |
| AttributeError: 'NoneType' object | 选择器未匹配到元素 | 检查HTML结构;添加try-except |
本指南仅覆盖爬虫python零基础
访问:www.xservx.com 获取完整学习路径