Selenium 入门
开始学习使用 Selenium,这是一款用于浏览器自动化和抓取 JavaScript 渲染内容的强大工具。
Selenium 入门 是 CoddyKit 上的免费 Web Scraping & Bots 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web Scraping & Bots 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web Scraping & Bots 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Dynamic Content Challenge
Most websites today aren't static pages. They use JavaScript to load content after the initial page renders.
Think of social media feeds, search results that update as you scroll, or interactive forms. Traditional scraping tools (like Requests) often miss this content because they only fetch the initial HTML.
Meet Selenium WebDriver
Selenium WebDriver is a powerful tool designed to automate web browsers. Unlike libraries that just fetch HTML, Selenium actually launches a real browser (like Chrome or Firefox).
This means it can execute JavaScript, interact with elements, and see the web page exactly as a human user would, making it perfect for dynamic content.
Selenium's Core Idea
Selenium works by sending commands to a specific browser driver (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox).
- Your Python script tells the driver what actions to perform.
- The driver then controls the actual browser.
- The browser executes these actions (navigating, clicking, typing) and returns the updated page state or data.
Install Selenium Library
First, let's install the Selenium library for Python. You can do this using pip, Python's package installer.
Open your terminal or command prompt and run:
pip install seleniumThis command downloads and installs the necessary Python components to interact with browsers.
Get Your Browser Driver
Selenium needs a specific browser driver to control your browser. For Chrome, you'll need ChromeDriver. For Firefox, it's GeckoDriver.
1. Check your browser version (e.g., Chrome -> Help -> About Google Chrome).
2. Download the matching driver from its official site:
- ChromeDriver: chromedriver.chromium.org
- GeckoDriver: github.com/mozilla/geckodriver
Place the downloaded driver executable (e.g., chromedriver.exe) in a location accessible by your system's PATH, or note its full path.
Launch Your First Browser
Let's write our first script to open a Chrome browser window using Selenium WebDriver.
Make sure your chromedriver is accessible (either in your PATH or specify its path directly in the Service object).
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
def main():
driver = None
try:
# IMPORTANT: Ensure ChromeDriver is installed and in your system PATH.
# If not, specify its path directly:
# service = Service("/path/to/your/chromedriver")
# driver = webdriver.Chrome(service=service)
driver = webdriver.Chrome() # Assumes chromedriver is in PATH
print("Chrome browser launched successfully!")
time.sleep(5) # Keep browser open for 5 seconds to observe
except Exception as e:
print(f"An error occurred: {e}")
finally:
if driver:
driver.quit() # Always close the browser
print("Browser closed.")
if __name__ == "__main__":
main()Go to a Web Page
Once the browser is open, you can tell it to navigate to any URL using the .get() method.
This is like typing a URL into the address bar and pressing Enter. The browser will load the page, including any JavaScript content.
from selenium import webdriver
import time
def main():
driver = None
try:
driver = webdriver.Chrome()
print("Browser launched.")
print("Navigating to example.com...")
driver.get("https://www.example.com")
print(f"Current page title: {driver.title}")
print(f"Current URL: {driver.current_url}")
time.sleep(5) # Keep browser open to see the page
except Exception as e:
print(f"An error occurred: {e}")
finally:
if driver:
driver.quit()
print("Browser closed.")
if __name__ == "__main__":
main()Waiting for Content
Web pages often take time to load completely, especially with dynamic content. Selenium provides ways to wait for elements to appear.
For now, we'll use a simple time.sleep() to pause execution. Later lessons will cover more robust explicit and implicit waits, which are more efficient.
time.sleep(seconds): Pauses execution for a fixed duration.
Always Close Your Browser
It's crucial to close the browser window when your script is done. This frees up system resources and prevents lingering browser processes.
Use the .quit() method on your WebDriver instance. This closes the browser and ends the WebDriver session cleanly.
from selenium import webdriver
import time
def main():
driver = None
try:
driver = webdriver.Chrome()
print("Browser launched.")
driver.get("https://www.example.com")
print(f"Navigated to: {driver.current_url}")
time.sleep(3) # Wait a bit to see the page
except Exception as e:
print(f"An error occurred: {e}")
finally:
if driver:
driver.quit() # This line closes the browser window
print("Browser closed successfully!")
if __name__ == "__main__":
main()Quick Check
You've launched your first browser with Selenium! What is the primary purpose of using Selenium WebDriver compared to libraries like Requests for web scraping?
Recap & Next Steps
In this lesson, you learned:
- Why Selenium is essential for handling dynamic web content.
- How to install the Selenium library and obtain a browser driver.
- To launch a browser, navigate to a URL, and close the session cleanly.
Next, we'll dive deeper into automating browser interactions like clicks, form submissions, and finding specific elements on a page!
常见问题解答
「Selenium 入门」课时是免费的吗?
是的 — 「Selenium 入门」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Scraping & Bots 课程的其余内容,请升级到 CoddyKit PRO。 Web Scraping & Bots 课程共包含 4 节课。
「Selenium 入门」这节课中我会学到什么?
开始学习使用 Selenium,这是一款用于浏览器自动化和抓取 JavaScript 渲染内容的强大工具。 你通过在浏览器中直接运行的动手代码来练习 Web Scraping & Bots,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web Scraping & Bots 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web Scraping & Bots 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「Selenium 入门」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web Scraping & Bots 课中编写并运行代码吗?
能。每节 Web Scraping & Bots 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Selenium 入门
- 自动化浏览器交互
- 从 JavaScript 中提取数据
- 动态页面的等待策略