python 爬虫selenium实例
时间: 2025-02-18 22:08:43 浏览: 36
使用Python和Selenium进行网页爬取的示例代码
为了展示如何利用Python与Selenium库实现基本的网页抓取功能,下面提供了一个简单的例子。此程序会启动Chrome浏览器实例,访问指定网站,并执行一些交互操作。
安装依赖项
在运行代码之前,请先安装必要的包:
pip install selenium webdriver-manager
示例代码:获取页面标题并打印出来
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
def setup_driver():
options = webdriver.ChromeOptions()
options.add_argument('--headless') # Run headlessly without opening an actual window
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
return driver
driver = setup_driver()
try:
url = 'http://example.com'
driver.get(url)
title = driver.title
print(f'The title of the webpage is {title}')
finally:
driver.quit()
这段脚本创建了一个无头模式下的Chrome驱动器对象[^2],加载目标URL http://example.com
并提取其
相关推荐


















