Python爬虫第五课:selenium自动化爬虫实战

Python爬虫第五课:selenium自动化爬虫实战

效果示列

代码示列

python 复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import time

def baidu_main():
    # 指定 ChromeDriver 的路径,若已配置环境变量,可省略路径参数
    service = Service(executable_path=r"E:\python_server\chromedriver-win64\chromedriver.exe")
    # 创建 Chrome 浏览器驱动实例
    driver = webdriver.Chrome(service=service)

    try:
        # 打开百度首页
        driver.get('https://www.baidu.com/')

        # 找到搜索框元素并输入关键词
        search_box = driver.find_element(By.ID, 'kw')
        search_box.send_keys('我是谁')

        # 找到搜索按钮并点击
        search_button = driver.find_element(By.ID, 'su')

        search_button.click()

        # 等待页面加载
        time.sleep(10)

        # 获取搜索结果页面的标题
        page_title = driver.title
        print(f"搜索结果页面的标题是: {page_title}")

    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        # 关闭浏览器
        driver.quit()

if __name__ == "__main__":
    baidu_main()