小白也能懂的 Selenium 教程:从入门到实战爬取网页数据
作为编程新手,你是否想过让电脑像真人一样操作浏览器?自动打开网页、输入文字、点击按钮,甚至爬取想要的数据?今天就带大家从零开始学习 Selenium,用最通俗的语言 + 实战代码,让你快速上手这个强大的工具。
一、先搞懂:Selenium 到底是个啥?
1. 核心定义
Selenium 本质是一个浏览器自动化工具,简单说就是:你写几行代码,就能让浏览器自动执行点击、输入、翻页、搜索等操作,和真人操作一模一样。
2. 和 requests 库的区别(新手必看)
- requests 库:只能获取网页的原始代码,遇到需要加载的动态内容(比如滚动后才显示的图片、评论)就抓不到;
- Selenium:直接驱动真实浏览器(Chrome/Edge/Firefox),会像人一样渲染网页,能拿到最终显示的所有内容。
3. 为什么能控制浏览器?
浏览器厂商会提供对应的「驱动程序」(比如 Edge 的 msedgedriver、Chrome 的 chromedriver),Selenium 通过这个驱动程序和浏览器内核通信,从而控制浏览器操作。
二、准备工作:5 分钟搞定环境搭建
1. 安装 Selenium 库
打开命令行,复制粘贴这行代码(用国内镜像,下载更快):
bash
运行
pip install selenium==4.11.0 -i https://pypi.mirrors.ustc.edu.cn/simple/
2. 下载浏览器驱动
以 Edge 为例(新手推荐,Windows 自带):
- 下载地址:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
- 注意:驱动版本要和你的 Edge 浏览器版本匹配;
- 解压后把驱动文件放到 Python 安装目录的「Scripts」文件夹里(比如
C:Python39Scripts)。
Chrome/Firefox 驱动下载地址也给大家:
- Chrome:https://chromedriver.storage.googleapis.com/index.html
- Firefox:https://github.com/mozilla/geckodriver/releases
三、基础操作:从打开网页开始
1. 第一个案例:打开指定网页
先看代码,每一行都有详细解释,新手直接复制就能跑:
python
运行
from selenium import webdriver # 导入驱动浏览器的核心模块
from selenium.webdriver.edge.options import Options # 导入浏览器配置类
# 1. 配置Edge浏览器
edge_options = Options()
# 关键:指定你的Edge安装路径(新手直接复制,大概率通用)
edge_options.binary_location = r"C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
# 2. 启动浏览器
driver = webdriver.Edge(options=edge_options)
# 3. 打开网页(比如人民邮电出版社官网)
driver.get('https://www.ptpress.com.cn/')
# 暂停脚本,让你看效果(按回车继续)
input('看完后按回车键关闭浏览器')
运行效果:会自动弹出 Edge 浏览器,打开指定网页,直到你按回车才结束。
2. 进阶:打开多个标签页
想同时打开百度、CSDN、B 站?用execute_script执行 JS 代码就能实现:
python
运行
from selenium import webdriver
from selenium.webdriver.edge.options import Options
edge_options = Options()
edge_options.binary_location = r"C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
driver = webdriver.Edge(options=edge_options)
# 先打开百度
driver.get('https://www.baidu.com/')
# 再打开CSDN(覆盖当前标签)
driver.get('https://www.csdn.net/')
# 用JS打开新标签页:_blank=新标签,_self=覆盖当前
driver.execute_script("window.open('https://www.bilibili.com/','_self');") # 覆盖当前
driver.execute_script("window.open('https://www.bilibili.com/','_blank');") # 新标签
input('按回车结束')
3. 关键技能:获取网页渲染后的代码
这是 Selenium 的核心优势!不管网页多动态,都能拿到最终的 HTML 代码:
python
运行
from selenium import webdriver
from selenium.webdriver.edge.options import Options
edge_options = Options()
edge_options.binary_location = r"C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
driver = webdriver.Edge(options=edge_options)
# 打开百度
driver.get('https://www.baidu.com')
# 获取渲染后的完整网页代码
print(driver.page_source)
用途:爬取数据前,先拿到完整代码,再从中提取需要的内容。
四、核心操作:模拟用户输入和点击
1. 向网页输入文字
比如在输入框里输入「Python」,关键是用find_element定位输入框:
python
运行
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By # 导入定位元素的工具
edge_options = Options()
edge_options.binary_location = r"C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
driver = webdriver.Edge(options=edge_options)
# 打开目标网站
driver.get('https://www.ryjiaoyu.com/')
# 定位input标签,输入「Python」
driver.find_element(by=By.TAG_NAME, value="input").send_keys("Python")
input('按回车结束')
2. 输入 + 搜索:按下回车键
输入关键词后自动搜索,只需加Keys.ENTER模拟回车:
python
运行
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.keys import Keys # 导入键盘按键
from selenium.webdriver.common.by import By
edge_options = Options()
edge_options.binary_location = r"C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
driver = webdriver.Edge(options=edge_options)
# 打开B站
driver.get('http://www.bilibili.com')
# 定位输入框,输入Python并按回车搜索
driver.find_element(by=By.TAG_NAME, value="input").send_keys("Python" + Keys.ENTER)
input('按回车结束')
3. 模拟点击按钮 / 链接
比如在 B 站点击「电影」分类,核心是click()方法:
python
运行
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
edge_options = Options()
edge_options.binary_location = r"C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
driver = webdriver.Edge(options=edge_options)
# 打开B站
driver.get('https://www.bilibili.com/')
# 定位所有a标签(链接)
elements = driver.find_elements(by=By.TAG_NAME, value="a")
# 遍历找到「电影」并点击
for element in elements:
if element.text == '电影':
element.click()
break
input('按回车结束')
五、实战案例 1:百度识图自动上传图片
无需手动点击上传,代码直接搞定图片识别:
python
运行
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
import time
edge_options = Options()
# 无头模式:不显示浏览器窗口,后台运行(注释掉就能看到界面)
# edge_options.add_argument('--headless')
edge_options.binary_location = r"C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
driver = webdriver.Edge(options=edge_options)
# 打开百度识图
driver.get('https://graph.baidu.com/pcpage/index?tpl_from=pc')
# 定位文件上传框,传入图片路径(替换成你的图片路径)
input_element = driver.find_element(by=By.NAME, value="file")
input_element.send_keys(r"C:Users9947Desktop est.png")
# 等待识别结果加载
time.sleep(5)
# 获取识别结果
result = driver.find_element(by=By.CLASS_NAME, value="graph-guess-word")
print("识别结果:", result.text)
input('按回车结束')
六、实战案例 2:爬取苏宁易购商品评论
这是新手最实用的案例!自动爬取商品的好评和差评,保存到本地文件:
python
运行
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
import time
# 1. 初始化浏览器
edge_options = Options()
edge_options.binary_location = r"C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
driver = webdriver.Edge(options=edge_options)
# 2. 定义获取评论的函数(复用代码)
def get_comment_content(file):
"""获取当前页的评论内容,写入文件"""
# 定位所有评论内容标签
comment_elements = driver.find_elements(by=By.CLASS_NAME, value='body-content')
for element in comment_elements:
file.write(element.text + '
') # 写入评论,换行分隔
# 3. 爬取好评
print("开始爬取好评...")
driver.get('https://review.suning.com/cluster_cmmdty_review/cluster-38249278-000000012389328846-0000000000-1-good.htm?originalCmmdtyType=general&safp=d488778a.10004.loverRight.166')
hp_file = open('好评.txt', 'w', encoding='utf8')
get_comment_content(hp_file) # 获取第一页好评
# 翻页爬取所有好评
next_btn = driver.find_elements(by=By.XPATH, value='//a[@class="next rv-maidian "]')
while next_btn != []:
next_btn[0].click()
time.sleep(1) # 等待页面加载
get_comment_content(hp_file)
next_btn = driver.find_elements(by=By.XPATH, value='//*[@class="next rv-maidian "]')
hp_file.close()
print("好评爬取完成,已保存到「好评.txt」")
# 4. 爬取差评(逻辑和好评一致)
print("开始爬取差评...")
driver.get('https://review.suning.com/cluster_cmmdty_review/cluster-38249278-000000012389328846-0000000000-1-bad.htm?originalCmmdtyType=general&safp=d488778a.10004.loverRight.166')
cpj_file = open('差评.txt', 'w', encoding='utf8')
get_comment_content(cpj_file)
# 翻页爬取所有差评
next_btn = driver.find_elements(by=By.XPATH, value='//*[@class="next rv-maidian "]')
while next_btn != []:
next_btn[0].click()
time.sleep(2)
get_comment_content(cpj_file)
next_btn = driver.find_elements(by=By.XPATH, value='//*[@class="next rv-maidian "]')
cpj_file.close()
print("差评爬取完成,已保存到「差评.txt」")
# 关闭浏览器
driver.quit()
七、新手避坑指南
- 驱动版本不匹配:浏览器和驱动版本必须一致,否则会报错;
- 元素定位失败:网页加载需要时间,可加
time.sleep()等待,或用更精准的定位方式(比如 XPATH); - 路径问题:文件路径要加
r(比如r"C: est.png"),避免转义符出错; - 反爬机制:爬取数据时不要太快,加
sleep模拟真人操作,避免被封 IP。
八、总结
Selenium 的核心就是「模拟真人操作浏览器」,新手入门只需掌握 3 个核心:
- 环境搭建:安装库 + 配置驱动;
- 元素定位:用
find_element找到输入框、按钮、链接等; - 模拟操作:
send_keys()输入、click()点击、page_source获取代码。
从打开网页到爬取评论,今天的案例覆盖了新手最常用的场景,代码直接复制就能跑。建议大家先跑通基础案例,再修改参数(比如换网址、换定位方式),慢慢就能灵活运用啦!






