本文最后更新于 2025年7月11日 下午
0、简介 ✨
Selenium 可以在无人参与的情况下自动操作浏览器,通过代码模拟用户行为,实现自动化流程,比如输入文本、提交表单等。
1、安装 🛠️
- 安装 selenium 库
- 查看浏览器版本(确保驱动匹配)

- 下载对应浏览器驱动
下载与你浏览器版本匹配的驱动文件,放到 Python 项目根目录。


2、演示代码 💻
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import time from selenium import webdriver from selenium.webdriver.common.by import By
input_location = (By.XPATH, '//*[@id="ww"]') button_location = (By.XPATH, '//*[@id="s_btn_wr"]') news_location = (By.XPATH, '//*[@id="1"]/div/h3/a')
chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--incognito") chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"])
browser = webdriver.Chrome(options=chrome_options) browser.get("https://news.baidu.com/") browser.maximize_window() browser.implicitly_wait(5)
browser.find_element(*input_location).send_keys("熊猫") browser.find_element(*button_location).click() text = browser.find_element(*news_location).text print(text)
time.sleep(3) browser.quit()
|

3、参数扩展及优化 ⚙️
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| """ 初始化 Chrome 浏览器配置 """ chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--incognito")
chrome_options.add_argument("--disable-cache") chrome_options.add_argument("--disable-plugins") chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("--disable-component-update") chrome_options.add_argument("--ignore-certificate-errors") chrome_options.add_experimental_option("useAutomationExtension", False) chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"])
browser = webdriver.Chrome(options=chrome_options) browser.maximize_window() browser.implicitly_wait(5)
""" 初始化 Firefox 浏览器配置 """ from selenium.webdriver.firefox.options import Options
firefox_options = Options()
firefox_options.set_preference("app.update.auto", False) firefox_options.set_preference("app.update.enabled", False) firefox_options.set_preference("browser.ssl_override_behavior", 1) firefox_options.set_preference("dom.webnotifications.enabled", False) firefox_options.set_preference("browser.dom.window.dump.enabled", False) firefox_options.set_preference("browser.console.showInPanel", False) firefox_options.set_preference("toolkit.telemetry.reportingpolicy.firstRun", False)
browser = webdriver.Firefox(options=firefox_options) browser.maximize_window() browser.implicitly_wait(5)
|
如果你想快速上手浏览器自动化,Selenium 是非常实用的利器!💪
在日常任务、测试自动化、爬虫等场景都能派上用场~