大家好,我是python网络爬虫这门课程的主要讲师geo
Selenium 是一个开源的 Web 自动化测试框架,主要用于模拟用户在浏览器中的操作,比如点击、输入、页面跳转、抓取数据等。 它最初是为 Web 应用自动化测试 设计的,但现在也常用于 爬虫 和 自动化任务。
动态网页的内容是由 JavaScript 在页面加载后动态生成的,常规的 requests 抓不到这些数据。这时我们就需要 Selenium,它能模拟用户操作浏览器,加载完整页面后再提取内容。
pip install selenium
下载 GeckoDriver(Chrome 的驱动)
https://googlechromelabs.github.io/chrome-for-testing/
下载 GeckoDriver(Firefox 的驱动)
GeckoDriver 的 GitHub 发布页面
https://github.com/mozilla/geckodriver/releases
演示一个 Selenium 打开网页并搜索的例子
需要指定geckodriver路径
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.by import By
import time
# 指定 geckodriver 路径
service = Service(executable_path='geckodriver路径')
# 初始化 Firefox 浏览器
firefox = webdriver.Firefox(service=service)
# 打开动态网页
firefox.get("https://www.google.com")
# 找到搜索框并输入内容
search_box = firefox.find_element(By.NAME, "q")
search_box.send_keys("Selenium Python")
search_box.send_keys(Keys.RETURN)
# 输出当前网页标题
print(firefox.title)
# 关闭浏览器
firefox.close()
无头模式(Headless Firefox)
无头模式可以后台运行,不弹出浏览器窗口
from selenium.webdriver.firefox.options import Options
options = Options()
options.add_argument("--headless") # 开启无头模式
driver = webdriver.Firefox(service=service, options=options)
请求等待
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, "class-name")))
print(element.text)
取得文本 / 属性
title_text = driver.find_element(By.TAG_NAME, "h1").text
print(title_text)
image_src = driver.find_element(By.TAG_NAME, "img").get_attribute("src")
print(image_src)