- 环境配置请参考上篇文章
- selenium包引入
pip install selenium
Selenium 可以模拟用户在浏览器中的操作,如点击按钮、填写表单、提交数据等,用于自动化测试 Web 应用程序,执行各种自动化任务。
-
代码实现
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import selenium # 较新版本中某些获取元素方法格式不通 print(selenium.__version__) # 创建浏览器驱动对象 # 创建浏览器对象 -不自动关闭(不设置options运行结束会自动关闭浏览器) options = Options() options.add_experimental_option("detach", True) driver = webdriver.Chrome(options=options) # 打开 百度 搜索页面 driver.get("https://www.baidu.com") # 找到搜索框并输入内容 # search_box = driver.find_element_by_name("wd") # 4.3.0版本中移除该方法,我们需要将代码改成如下形式 search_box = driver.find_element("name","wd") # 在搜索框中输入要搜索的内容 search_box.send_keys("123") # 模拟键盘按下回车键,提交搜索 search_box.send_keys(Keys.RETURN) # 关闭浏览器 #driver.quit()
-
运行结果